Mac OS X,  Mac OS X Server,  Mac Security,  Ubuntu,  Unix

Using Inputs in Bash Scripts

You can easily accept user provided input in bash by using the read command in bash for Linux and OS X. Here, we’ll echo out a choice to a user in a script, read the output into a variable called yn and then echo out the response:

echo "Please enter y or n: "
read yn
echo "You chose wrong: $yn"

Here, we used echo to simply write out what was chosen in the input. But we could also take this a little further and leverage a case statement to then run an action based on the choice selected:

read -p "Should the file extension change warning be disabled (y/n)? " yn
case ${yn:0:1} in
y|Y )
defaults write com.apple.finder FXEnableExtensionChangeWarning -bool false
echo "The warning has been disabled"
;;
* )
defaults write com.apple.finder FXEnableExtensionChangeWarning -bool true
echo "The warning has been enabled"
;;
esac

The options when scripting are pretty much infinite and chances are, if you’ve written any scripts, you’ll know of a better way to do this than how I’ve always done it. One of the great things about scripting is the fact that there’s always a better way. So feel free to throw any of your examples into the comments!