Dump the code

Bash scripting : the basic

Created 8 months ago
Posted By admin
3min read
Bash, short for "Bourne Again SHell" is a command processor that typically runs in a text window where the user types commands that cause actions. It's the default shell for most Unix-like systems and is available on Linux, macOS, and other platforms.

Bash scripting allows you to automate repetitive tasks, create complex workflows, and handle system administration tasks more efficiently. With Bash, you can write scripts to interact with files, directories, processes, and system commands, making it a powerful tool for both beginners and experienced users.

1. Creating a Bash Script:

Create a new file with a '.sh' extension, for example, 'myscript.sh'. Use a text editor like 'nano', 'vim', or 'gedit':

nano myscript.sh

2. Shebang:

Start your script with a shebang line. This tells the system which interpreter to use.

#!/bin/bash

3. Variables:

Declare variables without spaces around the `=` sign:

name="John"
age=25

4. User Input:

echo "Enter your name:"
read username
echo "Hello, $username!"

5. Conditionals:

if [ "$age" -ge 18 ]; then
  echo "You are an adult."
else
  echo "You are a minor."
fi

6. Loops:

  • For Loop:

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

  • While Loop:

count=0
while [ $count -lt 5 ]; do
  echo $count
  ((count++))
done

7. Functions:

my_function() {
  echo "This is a function."
}

my_function

8. Command Line Arguments:

echo "Script name: $0"
echo "First argument: $1"
echo "Second argument: $2"

9. Exit Status:

command
if [ $? -eq 0 ]; then
  echo "Command successful."
else
  echo "Command failed."
fi

10. File Operations:

# Check if a file exists
if [ -e "file.txt" ]; then
  echo "File exists."
fi

# Read lines from a file
while IFS= read -r line; do
  echo "$line"
done < "file.txt"

11. Permissions:

# Make a script executable
chmod +x myscript.sh

# Run the script
./myscript.sh

12. Commenting:

Use `#` for comments:

# This is a comment

13. Special Variables:

- '$0': Script name
- '$1', '$2', ...: Command line arguments
- '$#': Number of command line arguments
- '$?': Exit status of the last command
- '$$': Process ID of the current script
- '$USER': Current user
- '$HOME': Home directory

Example Script:

#!/bin/bash

name="John"
age=25

echo "Hello, $name!"
echo "You are $age years old."

if [ "$age" -ge 18 ]; then
  echo "You are an adult."
else
  echo "You are a minor."
fi

Remember to make your script executable with 'chmod +x myscript.sh' and execute it with './myscript.sh'.

This is just the tip of the iceberg; Bash scripting can get very complex and powerful. As you become more comfortable, you can explore more advanced topics such as arrays, string manipulation, and external commands.
Topics

Mastering Nginx

27 articles

Bash script

2 articles

Crontab

2 articles