Questions tagged [bash]

This tag is for questions about scripts written for the Bash command shell. For shell scripts with syntax or other errors, please check them at https://shellcheck.net before posting them here. Questions about the interactive use of Bash are more likely to be on-topic on Unix & Linux Stack Exchange or Super User than on Stack Overflow.

About Bash

There are a variety of interpreters that receive commands either interactively or as a sequence of commands from a file. The Bourne-again shell (Bash) is one such interpreter. Bash implements the standard Bourne Shell (sh), and offers numerous additions.

From the Free Software Foundation's Bash page:

Bash is an sh-compatible shell that incorporates useful features from the KornShell (ksh) and C shell (csh). It is intended to conform to the IEEE POSIX P1003.2/ISO 9945.2 Shell and Tools standard. It offers functional improvements over sh for both programming and interactive use. In addition, most sh scripts can be run by Bash without modification.

Read the Bash manual for technical details.

Bash was written by Brian Fox and first released in 1989. It is the default shell in many Linux distributions; it is available on most modern operating systems, and has been ported to Windows 10.

A note regarding versions

As of September 2022, the most recent version of bash is 5.2, although you may be using an older version depending on your operating system and which updates to bash have been installed. Most Linux installations should be using something in the 4.x family. macOS (formerly Mac OS X) only provides version 3.2 due to licensing issues.

Be sure to note in your question what version of bash you are using. This will alert potential answerers to what features are available to you, as well as which bugs may need to be worked around.

You can determine which version of bash you are using by running bash --version or checking the value of the BASH_VERSION shell variable.

Without an explicit version, an answerer may well assume you are using at least version 4.2 (it's been available for over 10 years). Questions tagged imply version 3.2 unless otherwise stated.

A Brief Release History

Based on downloads available from http://ftp.gnu.org/gnu/bash/

Version Release Date
3.2 2006-10-11
4.0 2009-02-20
4.1 2009-12-31
4.2 2011-02-13
4.3 2014-02-26
4.4 2016-09-15
5.0 2019-01-07
5.1 2020-12-06
5.2 2022-09-26

Additionally, all versions for bash from 2.0 and later received an important patch-level release to address the Shellshock vulnerability in September 2014.

Before asking about problematic code

To help the kind people who assist you, to ensure that future readers can benefit from your question, and to help ensure your question is voted up as useful for that lovely karma, please make your question as simple and universal as possible:

  1. Check whether your script or data has DOS style end-of-line characters

    • Use cat -v yourfile or echo "$yourvariable" | cat -v .

      DOS carriage returns will show up as ^M after each line.

      If you find them, delete them using dos2unix (a.k.a. fromdos) or tr -d '\r'

  2. Make sure you run the script with bash, not sh

    • The first line in the script must be #!/bin/bash or #!/usr/bin/env bash.

      It must not be #!/bin/sh even if your system's /bin/sh is a symlink to /bin/bash

    • Run the script with ./yourscript or bash yourscript.

      Do not run it with sh yourscript.

      This applies even when sh is a symlink to bash.

  3. Find a small, self-contained example.

    • Don't include sections and commands unrelated to your problem.
    • Avoid complex commands that just serve to produce a value (include the value directly).
    • Avoid relying on external files. Create the files on the fly, include the data directly, or post a small example of a file in your question.
  4. Test your example. Make sure it runs and still shows the problem. Do not brush this off.

    • Reformatting for clarity often sidesteps pitfalls related to spacing and naming.
    • Refactoring for simplicity often sidesteps pitfalls related to subshells.
    • Mocking out files and data often sidesteps problems related to special characters.
    • Hours spent trying multiple things often leads to posting code from one version and errors from another.
  5. Check the example for common problems

    • Run your example through shellcheck or the online ShellCheck service to automatically check for common mistakes.
    • Browse Bash pitfalls and Bash beginner's mistakes as well as the Popular Questions section below for checklists of common issues.
    • Check your data for special characters, using cat -v yourfile or cat -v <<< "$yourvar". Be especially careful with carriage returns (shown as ^M).
  6. Please avoid tagging questions that are solely about external commands. The bash tag should be reserved for Bash-related problems, not any CLI problem you might have.

How to turn a bad script into a good question

For example, let's say you have a script for alerting you when a server is idle, but it keeps alerting even when the machine is not idle:

# Avoid code like this when asking about a problem
# It has irrelevant code and external dependencies, and is hard to read and run

while true
do
  load=$(wget -O - "http://$1/load.php" | grep "^load:" | cut -d: -f 2)
  if [[ $load=="0" ]]
  then
    mailx -s "System is idle" user@example.com <<< "The server is idle"
    break
  else
    echo "Waiting..."
    sleep 60
  fi
done
  1. The problem still occurs without the loop: Remove the loop from your question.
  2. The problem still occurs if you skip asking the server: Hard code the response (e.g. load=42)
  3. The problem still occurs without emailing: Use echo "Why does this run?"
  4. The problem still occurs when removing the else branch. Shorten it

We're now left with this small, self-contained example:

# Prefer code like this when asking about a problem
# It's small, simple and self contained, making it easy to read and run.

load=42
if [[ $load=="0" ]]
then
  echo "Why does this run?"
fi

Thanks for making your question simple and useful! Enjoy your upvotes!

(However, note that this example is simple to compare against the relevant entry in Bash pitfalls and the error is automatically caught by shellcheck, so now you don't actually need to ask!)

Popular Questions

Some frequently asked Bash questions include the following.

Basic Syntax and Common Newbie Problems

Some fundamentals of Bash are surprising even to veterans from other programming languages.

How Do I ...?

Why Does ...?

Common Tasks

These questions are not really specific to Bash, but frequent enough in this tag that they deserve to be included here.

Meta

Books and Resources

Additional reading materials include:

Tools

  • shellcheck - a static analysis tool that detects common mistakes
  • on-line ShellCheck, a web server providing shellcheck (useful if you've not yet installed the program)
  • https://explainshell.com/ can pick apart many command lines and explain what the elements mean (notice that you can sometimes click on a result to have it picked apart further)

Chat

The Stack Overflow bash chat is useful for coordinating work within this tag, and perhaps occasionally for getting quick help (though no guarantees can be made; attendance is spotty).

154003 questions
1209
votes
15 answers

Defining a variable with or without export

What is export for? What is the difference between: export name=value and name=value
flybywire
  • 261,858
  • 191
  • 397
  • 503
1152
votes
9 answers

How to iterate over arguments in a Bash script

I have a complex command that I'd like to make a shell/bash script of. I can write it in terms of $1 easily: foo $1 args -o $1.ext I want to be able to pass multiple input names to the script. What's the right way to do it? And, of course, I…
Thelema
  • 14,257
  • 6
  • 27
  • 35
1142
votes
16 answers

How do I clear/delete the current line in terminal?

If I'm using terminal and typing in a line of text for a command, is there a hotkey or any way to clear/delete that line? For example, if my current line/command is something really long like: > git log --graph --all --blah..uh oh i want to cancel…
triad
  • 20,407
  • 13
  • 45
  • 50
1117
votes
24 answers

Get current directory or folder name (without the full path)

How could I retrieve the current working directory/folder name in a bash script, or even better, just a terminal command. pwd gives the full path of the current working directory, e.g. /opt/local/bin but I only want bin.
Derek Dahmer
  • 14,865
  • 6
  • 36
  • 33
1115
votes
18 answers

Shell: How to call one shell script from another shell script?

I have two shell scripts, a.sh and b.sh. How can I call b.sh from within the shell script a.sh?
Praveen
  • 11,459
  • 4
  • 16
  • 7
1114
votes
13 answers

In Bash, how can I check if a string begins with some value?

I would like to check if a string begins with "node" e.g. "node001". Something like if [ $HOST == node* ] then echo yes fi How can I do it correctly? I further need to combine expressions to check if HOST is either "user1" or begins with…
Tim
  • 1
  • 141
  • 372
  • 590
1103
votes
15 answers

How do I use sudo to redirect output to a location I don't have permission to write to?

I've been given sudo access on one of our development RedHat linux boxes, and I seem to find myself quite often needing to redirect output to a location I don't normally have write access to. The trouble is, this contrived example doesn't work: sudo…
Jonathan
  • 25,873
  • 13
  • 66
  • 85
1090
votes
10 answers

What does set -e mean in a bash script?

I'm studying the content of this preinst file that the script executes before that package is unpacked from its Debian archive (.deb) file. The script has the following code: #!/bin/bash set -e # Automatically added by dh_installinit if [ "$1" =…
AndreaNobili
  • 40,955
  • 107
  • 324
  • 596
1086
votes
26 answers

Extract substring in Bash

Given a filename in the form someletters_12345_moreleters.ext, I want to extract the 5 digits and put them into a variable. So to emphasize the point, I have a filename with x number of characters then a five digit sequence surrounded by a single…
Berek Bryan
  • 13,755
  • 10
  • 32
  • 43
1085
votes
11 answers

How do I pause my shell script for a second before continuing?

I have only found how to wait for user input. However, I only want to pause so that my while true doesn't crash my computer. I tried pause(1), but it says -bash: syntax error near unexpected token '1'. How can it be done?
user3268208
1077
votes
10 answers

How do I put an already-running process under nohup?

I have a process that is already running for a long time and don't want to end it. How do I put it under nohup (that is, how do I cause it to continue running even if I close the terminal?)
flybywire
  • 261,858
  • 191
  • 397
  • 503
1073
votes
50 answers

Set environment variables from file of key/value pairs

TL;DR: How do I export a set of key/value pairs from a text file into the shell environment? For the record, below is the original version of the question, with examples. I'm writing a script in bash which parses files with 3 variables in a certain…
hugo19941994
  • 10,942
  • 3
  • 17
  • 13
1071
votes
24 answers

How to permanently set $PATH on Linux/Unix

On Linux, how can I add a directory to the $PATH so it remains persistent across different sessions? Background I'm trying to add a directory to my path so it will always be in my Linux path. I've tried: export PATH=$PATH:/path/to/dir This works,…
Ali
  • 261,656
  • 265
  • 575
  • 769
1057
votes
25 answers

Recursively counting files in a Linux directory

How can I recursively count files in a Linux directory? I found this: find DIR_NAME -type f ¦ wc -l But when I run this it returns the following error. find: paths must precede expression: ¦
Robert Buckley
  • 11,196
  • 6
  • 24
  • 25
1035
votes
18 answers

Add line break to 'git commit -m' from the command line

I am using Git from the command line and am trying to add a line break to the commit message (using git commit -m "") without going into Vim. Is this possible?
Alan Whitelaw
  • 16,171
  • 9
  • 34
  • 51