Home > Environment & Utility > sh

sh: Shell Script Execution and Command Interpretation

sh is a Bourne shell-compatible command interpreter. It is used to execute scripts or process commands interactively. On most Linux systems, /bin/sh is a symbolic link to another shell like bash or dash, providing a script execution environment that adheres to the POSIX standard.

Overview

`sh` is one of the default shells on Unix and Linux systems, used for script execution and interactive command processing. Its strict adherence to the POSIX standard makes scripts written for `sh` highly portable across various systems.

Key Features

  • POSIX Compatibility: Provides a foundation for writing standard shell scripts.
  • Script Execution: Runs sequences of commands stored in files.
  • Interactive Command Interpretation: Processes commands directly entered by the user.
  • System Default: Typically pre-installed on most Unix/Linux systems.

Key Options

`sh` offers various options that affect script execution behavior and debugging.

Script Execution and Debugging

Generated command:

Try combining the commands.

Description:

`sh` Executes the command.

Combine the above options to virtually execute commands with AI.

Usage Examples

Executing a Script File

sh my_script.sh

Executes a specified shell script file using `sh`.

Executing a Command String Directly

sh -c "echo 'Hello from sh!' && ls -l"

Uses the `-c` option to execute a quoted command string with `sh`.

Executing a Script in Debug Mode

sh -x debug_script.sh

Uses the `-x` option to trace script execution for debugging purposes.

Executing Commands from Standard Input

echo "ls -a" | sh

Executes commands passed via a pipe using `sh`.

Exiting Immediately on Error

sh -e error_prone_script.sh

Ensures the script terminates immediately if an error occurs.

Tips & Notes

`sh` is a powerful tool, but it's important to understand its differences from other shells.

When Writing Scripts

  • It's good practice to start scripts with #!/bin/sh to explicitly indicate that the script should be executed by sh.
  • Extended features of other shells like bash or zsh (e.g., arrays, advanced pattern matching, [[ ... ]] conditionals) may not work in sh. Therefore, only use POSIX-compliant syntax.
  • The -x option is very useful for debugging, helping to understand script flow and variable values.

Compatibility

On most Linux distributions, /bin/sh is a symbolic link to dash (Debian/Ubuntu family) or bash (Red Hat/Fedora family). Consequently, sh scripts run in the POSIX-compliant mode of the linked shell. This means they might behave differently from bash scripts.



Same category commands