The author Fizer Khan is a Shell script fan who is so obsessed with novel and interesting things about Shell scripts. He recently encountered an authy-ssh script. He learned a lot of useful and cool things to alleviate the problem of dual authentication on the ssh server. He wants to share this with you.
1. color the output
In most cases, you want to output results with colors. For example, Green indicates success, red indicates failure, and yellow indicates warning.
Shell code
- NORMAL=$(tput sgr0)
- GREEN=$(tput setaf 2; tput bold)
- YELLOW=$(tput setaf 3)
- RED=$(tput setaf 1)
- function red() {
- echo -e "$RED$*$NORMAL"
- }
- function green() {
- echo -e "$GREEN$*$NORMAL"
- }
- function yellow() {
- echo -e "$YELLOW$*$NORMAL"
- }
- # To print success
- green "Task has been completed"
- # To print error
- red "The configuration file does not exist"
- # To print warning
- yellow "You have to use higher version."
Here, tput is used to set the color and text and reset to the normal color. For more information about tput, see prompt-color-using-tput.
2. Output debugging information
To output debugging information, you only need to debug and set the flag.
Shell code
- function debug() {
- if [[ $DEBUG ]]
- then
- echo ">>> $*"
- fi
- }
- # For any debug message
- debug "Trying to find config file"
Some geeks also provide online debugging:
Shell code
- # From cool geeks at hacker news
- function debug() { ((DEBUG)) && echo ">>> $*"; }
- function debug() { [ "$DEBUG" ] && echo ">>> $*"; }
3. check whether a specific executable file exists?
Shell code
- OK=0
- FAIL=1
- function require_curl() {
- which curl &>/dev/null
- if [ $? -eq 0 ]
- then
- return $OK
- fi
- return $FAIL
- }
Here we use the which command to find the executable curl path. If the execution succeeds, the executable file exists, and vice versa. Set &>/dev/null in the output stream, and the error stream will display to/dev/null, which means there is nothing to print on the control panel ).
Some geeks suggest returning Code directly by returning which.