Horray... Its time to some shell script tips. In this article I'm going to use the "/bin/bash" interpreter, that is present in the vast majority of Linux installations, and even Unix or MacOS.
Let's see some isolated tips and at the end we'll put them together.
PID of your own Process
There are some variables that bash already give to us, like these:
- $$ ↣ The PID of the running process
- $PPID ↣ The Parent PID of the running process
#!/bin/bash
echo "My PID is " $$
echo "My Parent PID is " $PPID
Create a temp file
Use the "mktemp" command to create a temp file. Remember to remove it at the end of the execution of your shell script.
#!/bin/bash
# Create a temp file
FILE=`mktemp`
echo $FILE
# Dont forget to remove the file
rm -f $FILE
UpperCase or LowerCase
An easy way to transform your variable in UpperCase or LowerCase. Its not necessary any complex command with "awk", "sed", "regex", or other, just the built-in power of bash.
#!/bin/bash
VALUE="This Monday is very Hot"
echo "In Uppercase: ${VALUE^^}"
echo "In Lowercase: ${VALUE,,}"
Ask the user for some input
Lets use the "read" command to accomplish this.
#!/bin/bash
read -p "Do you want to continue? [Y/n]" A
if [ ! "${A}" == "Y" ]; then
echo "Stopping now"
exit 1
fi
exit 0
Echo with Colors? Yes, we can!
#!/bin/bash
# COLORS
red='\e[1;31m'
green='\e[1;32m'
yellow='\e[1;33m'
blue='\e[1;34m'
magenta='\e[1;35m'
cyan='\e[1;36m'
# NoColor
NC='\e[0m\033[0m'
echo_color() {
echo -n -e "${1} ${NC}\n"
}
# Indicate the color that you want here
echo_color "${red}ERROR"
echo_color "${yellow}WARNING"
echo_color "${green}OK"
Script... Assemble!
#!/bin/bash
# Declare some colors
RED='\e[1;31m'
GREEN='\e[1;32m'
YELLOW='\e[1;33m'
BLUE='\e[1;34m'
MAGENTA='\e[1;35m'
CYAN='\e[1;36m'
# NoColor
NC='\e[0m\033[0m'
# Define the echo with color function
echo_color() {
echo -n -e "${1} ${NC}\n"
}
# Use this function to exit your script
# It centralizes the exit and removes the temp file
close() {
rm -f $FILE
exit $1
}
FILE=`mktemp`
# Lets save our PID in the temp FILE
echo "$$" > $FILE
read -p "Do you want to print the value in the $FILE? [Y/n]" A
if [[ "${A}" == "Y" || "${A}" == "" ]]; then
echo_color "${MAGENTA}`cat $FILE`"
else
echo_color "${YELLOW}Not showing own PID value"
fi
read -p "Do you want to save the Parent PID? [yes/no]" A
if [ "${A,,}" == "yes" ]; then
echo "$PPID" > $FILE
echo_color "${RED}`cat $FILE`"
else
echo_color "${YELLOW}Not showing Parent PID value"
fi
close 0