1. 5
  1.  

  2. 10

    The Python script in the article is really an example of how shell scripts are superior to Python for a lot of jobs.

    #!/usr/bin/env python3
    import subprocess, random, glob
    print('HERE WE GO')
    
    sounds = glob.glob('/Users/{yourName}/Library/Sounds/*.aiff')
    sound = random.choice(sounds)
    print('randomly selected sound: ', sound)
    command = 'defaults write .GlobalPreferences com.apple.sound.beep.sound /Users/{yourName}/Library/Sounds/{}.aiff'.format(sound)
    
    # You could also define an array of sounds yourself,  
    # if you don't want every .aiff file to be a possibility
    # sounds=['tabarnak1', 'tabarnak2', 'tabarnak3']
    # sound=random.choice(sounds)
    # command = 'defaults write .GlobalPreferences com.apple.sound.beep.sound /Users/{yourName}/Library/Sounds/{}.aiff'.format(sound)
    
    subprocess.call(command, shell=True)
    

    {yourName} could be fixed by using Python’s env or ~ expansion or whatever, but this is much simpler as a shell expansion: ~/Library/Sounds/*.aiff. Using the shell=True flag on subprocess makes the subprocess call totally unsafe and subject to being broken by files with spaces in them anyway. This script is functionally identical but safer:

    #!/bin/bash
    set -euo pipefail
    echo "HERE WE GO"
    local FILE=$(ls ~/Library/Sounds/*.aiff | sort --random-sort | head -n 1)
    echo "randomly selected sound: $FILE"
    defaults write .GlobalPreferences com.apple.sound.beep.sound "$FILE"
    
    1. 2
      ls ~/Library/Sounds/*.aiff | sort --random-sort | head -n 1
      

      can be simplified to

      shuf -n1 -e ~/Library/Sounds/*.aiff
      

      Checked with GNU shuf, works even with spaces in filenames, not sure about other implementations.

      1. 7

        I thought about shuf, but Mac doesn’t have shuf built-in, and this is meant to pick Mac sounds.