Useful Bash Scripts

Posted by:

|

On:

|

Prompt the user to press the Enter key before proceeding with the script execution.

read -p "Press enter key to continue..."

Check if a variable is empty

if [ "$name" == "" ]; then
  echo "name is empty"
fi

Transform any uppercase letters in the input word to their corresponding lowercase letters.

word="Hello WORLD"
echo "$(echo "$word" | tr 'A-Z' 'a-z')"

# hello world

Assign the current date to the variable date in the format “YYYYMMDD”.

date=`date +%Y%m%d`
echo "$date"

Find string length

mystring="Hello world"
length=${#mystring}
echo $length

Extract substring

Detailed explanation:

  • -d , : specify delimiter used in the input string. In this case, the delimiter is a comma (,).
  • -f 4 : specify the field number to be extracted from the input string. In this case, it is the fourth field.
  • <<< : pass the input string to the command.
cut -d , -f 4 <<< "Today,is,12th,April,2024"

# April

Find and Replace String

first="The apple is fresh"
second="orange"
echo "${first/apple/"$second"}" 

# The orange is fresh

Concatenate Strings

firststring="Hello "
secondstring="world !"
echo "$firststring$secondstring"

# Hello world !

Backup a file as an original copy if the original copy is not found.

Check whether a file named “$1.org” exists using the -f option.

if [ ! -f "$1.org" ]; then
  cp $1 "$1.org"
fi

Check if a Number is Even or Odd

mynumber=241
if [ $((mynumber%2)) -eq 0 ]; then
  echo "Your number is even"
else
  echo "Your number is odd."
fi

Create and add item to an array
Detailed explanation: use “fruitArray=(apple orange banana)” to create a new array. Add item to the array by “fruitArray+=(“$fruit”)”. The items are extracted from the array one by one using “${fruitArray[@]}”. Finally, to echo without a trailing newline (LF), you can use the -n option.

fruitArray=(apple orange banana)
while true; do
  echo "Enter a fruit (or 'q' to quit):"
  read fruit
  if [[ "$fruit" == "q" ]]; then
    break
  fi
  fruitArray+=("$fruit")
done
echo -n "Updated fruitArray:"
for i in "${fruitArray[@]}"; do
  echo -n "$i "
done

#Updated fruitArray: apple orange banana ….(items added by user)….

To check the number within an IP address

Detailed explanation: the value stored in the variable $MyIP is being echoed and then piped (|) to awk for further processing. -F. sets the field separator as a dot (“.”) . {print $2}' prints the second field ($2), which corresponds to the second section of the IP address.

MyIP="192.168.21.225"
echo $(echo $MyIP | awk -F. '{print $2}')

#168

Change the IP address, subnet mask and gateway of the Linux.

Detailed explanation: -i is an option for sed that enables in-place editing, meaning it modifies the files directly instead of writing the changes to the standard output. "s+address1.*+address1=${MyIP}/24,${GW}+": This is the sed expression used for substitution. It searches for lines that contain the pattern “address1” followed by any characters (.*) and replaces the entire line with the string “address1=${MyIP}/24,${GW}”. ${MyIP} and ${GW} are variables that should be replaced with actual IP addresses or values. The file store the network data is placed in a file in the /etc/NetworkManager/system-connections/ directory that have “1” in the filename. In the context of the sed command, the plus sign (+) is used as a delimiter in the search and replace pattern. It serves as an alternative to the commonly used forward slash (/) delimiter. Using different delimiters can improve the readability and ease of writing sed expressions, especially when dealing with complex patterns that contain forward slashes.

MyIP="192.168.21.26"
GW="192.168.21.253"
sed -i "s+address1.*+address1=${MyIP}/24,${GW}+" /etc/NetworkManager/system-connections/*1*

The new IP will be effective after a reboot.

To extract specific columns from a CSV file and assign them to variables based on a search match.

Detailed explanation: search for the value stored in the $name variable within the file “member.txt”. The -i flag makes the search case-insensitive. The output of the grep command is then piped (|) to awk. It then uses awk to extract specific fields (second, fourth and third field) from the matching lines. The -F, flag sets the field separator as a comma (“,”). Finally, the extracted values are assigned to the name, age, and height variables using the read command.

Content of csv file member.csv

1,Peter,160cm,12
2,Tom,175cm,16
3,Mary,170cm,15
name="Mary"
read name age height<<< $( grep -i $name member.txt | awk -F, '{print $2" "$4" "$3}' )
echo $name $age $height

#Mary 15 170cm

To search for lines that start with the pattern “cd ” in the file specified by the variable $filename.

Detailed explanation: check if there are any lines in the file specified by $filename that start with “cd “. The -c option in grep is used to count the number of matching lines. ^cd specifies that we are looking for lines starting with “cd “.

filename="file.txt"
echo $(grep -c "cd" $filename)

Posted by

in