[Bash] Controls flow

If

The if statement is used to execute commands based on a condition.

if [ condition ]; then
    commands
fi

Example: vim example.sh

#!/bin/zsh

echo "Enter a number: "
read number

if [ $number -gt 0 ]; then
  echo "The number is positive."
elif [ $number -lt 0 ]; then
  echo "The number is negative."
else
  echo "The number is zero."
fi

chmod +x example.sh

Case

The case statement is used to execute commands based on multiple conditions.

case value in
  pattern1)
    commands1
    ;;
  pattern2)
    commands2
    ;;
  *)
    default_commands
    ;;
esac

Example

#!/bin/zsh

echo "Enter a letter: "
read letter

case $letter in
  [a-z])
    echo "You entered a lowercase letter."
    ;;
  [A-Z])
    echo "You entered an uppercase letter."
    ;;
  *)
    echo "You entered a non-alphabet character."
    ;;
esac

For

The for loop is used to iterate over a list of items.

for item in list; do
  commands
done

Example:

#!/bin/zsh

for i in {1..5}; do
  echo "Number: $i"
done

Pratices:

# Write an if statement to check if a file named myfile.txt exists and print a message accordingly.

FILENAME="myfile.txt"
if [ -f $FILENAME ]; then
  echo "$FILENAME exists"
else
  echo "No such file"
fi


# Write a case statement to check if a variable color is "red", "green", or "blue" and print a message for each color.

echo "Enter a color: "
read color

case $color in
  red)
    echo "red'
    ;;
  blue)
    echo "blue"
    ;;
  green)
    echo "green"
    ;;
  *)
    echo "not find a match color"
    ;;

# Write a for loop to print the names of all files in the current directory.

for file in *; do
  if [ -f "$file" ]; then
    echo "File: $file"
    # size=$(stat -c%s "$file")
    size=$(stat -f%z "$file")
    echo "File: $file, Size: $size bytes"
  fi
done

Output:

File: if.sh, Size: 105 bytes
File: list_regular_files.sh
File: list_regular_files.sh, Size: 162 bytes

You can check the file size by using ls -lh as well

for file in *; do: This loop iterates over all items in the current directory.
if [ -f "$file" ]; then: Checks if the item is a regular file.

posted @ 2024-05-19 16:16  Zhentiw  阅读(6)  评论(0编辑  收藏  举报