SkillSprout
Chapter 2 · Lesson 1
Beginner
1 min read

Create and Run a Shell Script

Overview

A shell script is a text file containing commands that Bash executes from top to bottom. It is useful for repeated setup, checks and operational work. Every script should begin with a clear intention, validate input and return an exit status.

Detailed Notes

First script

bash
mkdir -p ~/linux-practice/scripts
cat > ~/linux-practice/scripts/hello.sh <<'EOF'
#!/usr/bin/env bash

echo "Hello, $USER"
EOF
chmod 755 ~/linux-practice/scripts/hello.sh
~/linux-practice/scripts/hello.sh

Line by line:

  • #!/usr/bin/env bash is the shebang. It tells a direct process launcher to run the file with Bash.
  • echo prints text.
  • $USER expands to the environment variable.
  • chmod 755 makes the file readable and executable.

Run methods:

bash
bash hello.sh
./hello.sh

bash hello.sh explicitly uses Bash. ./hello.sh requires the executable mode and follows the shebang.

Arguments

bash
cat > greet.sh <<'EOF'
#!/usr/bin/env bash

name="${1:-Learner}"
echo "Hello, $name"
EOF

$1 is the first argument. ${1:-Learner} uses Learner only when $1 is empty or missing.

bash
bash greet.sh
bash greet.sh Alex

Expected output differs based on the argument.

Exit status

bash
bash -n hello.sh
bash -n greet.sh
echo "$?"

bash -n performs syntax checking without running commands. $? holds the previous command's exit status. 0 means success in shell conventions.

Common Interview Questions

Finished this lesson?

0 of 25 lessons done · 0% of the course