Bird
Raised Fist0
Bash Scriptingscripting~10 mins

Portable scripting (POSIX compliance) in Bash Scripting - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Portable scripting (POSIX compliance)
Write script using POSIX syntax
↓
Avoid bash-specific features
↓
Use /bin/sh as interpreter
↓
Test script on different shells
↓
Script runs on any POSIX shell
↓
Success
Write scripts using only POSIX standard commands and syntax, avoid bash-only features, use /bin/sh, and test on multiple shells for portability.
Execution Sample
Bash Scripting
#!/bin/sh
for i in 1 2 3; do
  echo "Number $i"
done
A simple POSIX-compliant script that prints numbers 1 to 3 using a for loop.
Execution Table
StepActionVariable iOutput
1Start loop, i=11Number 1
2Next iteration, i=22Number 2
3Next iteration, i=33Number 3
4No more items, loop ends--
💡 Loop ends after i=3, no more items in list
Variable Tracker
VariableStartAfter 1After 2After 3Final
i-123-
Key Moments - 3 Insights
Why do we use #!/bin/sh instead of #!/bin/bash?
Using #!/bin/sh ensures the script runs with any POSIX-compliant shell, not just bash, increasing portability as shown in the execution_table where standard syntax is used.
What happens if we use bash-specific features like arrays?
Bash-specific features may cause errors on shells that only support POSIX, breaking portability. The execution_table shows only POSIX features to avoid this.
Why avoid syntax like [[ ... ]] in POSIX scripts?
[[ ... ]] is a bash extension not supported in POSIX shells. Using [ ... ] as in the example keeps scripts portable, as reflected in the simple loop syntax in the execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of variable i at Step 2?
A3
B1
C2
D-
💡 Hint
Check the 'Variable i' column at Step 2 in the execution_table.
At which step does the loop end according to the execution_table?
AStep 4
BStep 3
CStep 2
DStep 1
💡 Hint
Look at the 'Action' column describing loop termination in the execution_table.
If we replace /bin/sh with /bin/bash but keep POSIX syntax, what changes in the execution?
AScript will fail due to syntax errors
BScript runs the same, maintaining portability
CScript runs faster but output changes
DScript requires arrays to run
💡 Hint
Refer to the concept_flow and key_moments about interpreter choice and POSIX syntax.
Concept Snapshot
Portable scripting means writing shell scripts using only POSIX standard features.
Use #!/bin/sh as the interpreter.
Avoid bash-specific syntax like arrays or [[ ]].
Test scripts on different shells to ensure compatibility.
This ensures scripts run anywhere POSIX shells exist.
Full Transcript
Portable scripting in shell means writing scripts that work on any POSIX-compliant shell, not just bash. We do this by using the #!/bin/sh shebang line and avoiding bash-only features like arrays or [[ ... ]] tests. The example script uses a simple for loop and echo command, which are POSIX standard. The execution table shows the loop variable i taking values 1, 2, and 3, printing each number. The loop ends when no more items remain. Beginners often wonder why not use #!/bin/bash or bash features; the answer is portability. Using POSIX syntax ensures the script runs on many systems without modification. The quiz checks understanding of variable values during loop steps and the importance of interpreter choice. Remember, portable scripts are simple, standard, and widely compatible.

Practice

(1/5)
1. Which shebang line is best for writing a portable POSIX-compliant shell script?
easy
A. #!/bin/sh
B. #!/bin/bash
C. #!/usr/bin/env bash
D. #!/bin/zsh

Solution

  1. Step 1: Understand shebang purpose

    The shebang line tells the system which shell to use to run the script.
  2. Step 2: Identify POSIX-compliant shell

    "/bin/sh" is the standard POSIX shell available on most Unix-like systems, ensuring portability.
  3. Final Answer:

    #!/bin/sh -> Option A
  4. Quick Check:

    POSIX shell = #!/bin/sh [OK]
Hint: Use #!/bin/sh for best portability across Unix systems [OK]
Common Mistakes:
  • Using #!/bin/bash which may not exist on all systems
  • Using #!/usr/bin/env bash which depends on env and bash presence
  • Using #!/bin/zsh which is not POSIX standard
2. Which of the following is a POSIX-compliant way to write an if statement in a shell script?
easy
A. if [[ $var -eq 1 ]]; then echo yes; fi
B. if [ $var -eq 1 ]; then echo yes; fi
C. if (( $var == 1 )); then echo yes; fi
D. if test $var = 1; then echo yes; fi

Solution

  1. Step 1: Identify POSIX test syntax

    POSIX shell supports the single bracket [ ] syntax for tests.
  2. Step 2: Check each option

    if [ $var -eq 1 ]; then echo yes; fi uses [ $var -eq 1 ] which is POSIX compliant. if [[ $var -eq 1 ]]; then echo yes; fi uses [[ ]] which is bash-specific. if (( $var == 1 )); then echo yes; fi uses (( )) which is arithmetic syntax in bash. if test $var = 1; then echo yes; fi uses test but with = for numbers, which is string comparison, not numeric.
  3. Final Answer:

    if [ $var -eq 1 ]; then echo yes; fi -> Option B
  4. Quick Check:

    POSIX if test = [ ] syntax [OK]
Hint: Use single brackets [ ] for tests in POSIX scripts [OK]
Common Mistakes:
  • Using [[ ]] which is not POSIX
  • Using (( )) arithmetic syntax not POSIX
  • Using = for numeric comparison instead of -eq
3. What will be the output of this POSIX-compliant script snippet?
count=3
while [ $count -gt 0 ]; do
  echo $count
  count=$((count - 1))
done
medium
A. 3 2 1
B. 3 2 1 0
C. 1 2 3
D. Error: syntax not supported

Solution

  1. Step 1: Understand the loop condition

    The loop runs while count is greater than 0.
  2. Step 2: Trace the loop iterations

    Initial count=3, prints 3, decrements to 2; prints 2, decrements to 1; prints 1, decrements to 0; loop ends.
  3. Final Answer:

    3 2 1 -> Option A
  4. Quick Check:

    Loop prints 3 to 1, stops before 0 [OK]
Hint: Loop runs while count > 0, prints then decrements [OK]
Common Mistakes:
  • Expecting 0 to print
  • Confusing -gt with -ge
  • Thinking $(( )) is not POSIX (it is)
4. This script is intended to print all files in the current directory. What is the error?
for file in $(ls); do
  echo $file
 done
medium
A. The echo command is not POSIX compliant
B. Missing 'do' keyword in the for loop
C. Using $(ls) can break on filenames with spaces
D. Incorrect variable name 'file' used in loop

Solution

  1. Step 1: Analyze command substitution usage

    Using $(ls) splits output on whitespace, breaking on filenames with spaces.
  2. Step 2: Identify safer alternative

    Using 'for file in *' is POSIX compliant and handles spaces better.
  3. Final Answer:

    Using $(ls) can break on filenames with spaces -> Option C
  4. Quick Check:

    $(ls) splits on spaces, unsafe for filenames [OK]
Hint: Avoid $(ls); use 'for file in *' for portability [OK]
Common Mistakes:
  • Thinking 'do' is missing (it is present)
  • Assuming variable name matters
  • Believing echo is not POSIX compliant
5. You want to write a POSIX-compliant shell script using only built-in shell commands (no external utilities like grep, cat, wc) that reads lines from a file and counts how many lines contain the word 'error'. Which approach is portable and correct?
hard
A. grep -c 'error' filename
B. for line in $(cat filename); do if echo $line | grep -q 'error'; then count=$((count+1)); fi; done; echo $count
C. cat filename | grep 'error' | wc -l
D. while read line; do case "$line" in *error*) count=$((count+1)) ;; esac; done < filename; echo $count

Solution

  1. Step 1: Evaluate each option for POSIX compliance and correctness

    A: grep -c 'error' filename uses external grep utility. C: cat filename | grep 'error' | wc -l uses external cat, grep, wc utilities. B: while read line; do case "$line" in *error*) count=$((count+1)) ;; esac; done < filename; echo $count uses a while read loop with case pattern matching, fully POSIX compliant pure shell and handles lines safely. D: for line in $(cat filename); do if echo $line | grep -q 'error'; then count=$((count+1)); fi; done; echo $count uses for loop over $(cat filename) which breaks on spaces and uses external cat/grep.
  2. Step 2: Choose the safest and most portable method

    while read line; do case "$line" in *error*) count=$((count+1)) ;; esac; done < filename; echo $count is the best because it reads line by line safely and uses POSIX shell features only.
  3. Final Answer:

    while read line; do case "$line" in *error*) count=$((count+1)) ;; esac; done < filename; echo $count -> Option D
  4. Quick Check:

    Line-by-line read with case is portable and safe [OK]
Hint: Use while read and case for safe POSIX line processing [OK]
Common Mistakes:
  • Using external grep instead of pure shell constructs
  • Using for loop over command substitution breaking on spaces
  • Using unnecessary cat in pipelines
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard