Questions tagged [bash]

For questions about scripts written for the Bash command shell. For shell scripts with errors/syntax errors, please check them with the shellcheck program (or in the web shellcheck server at https://shellcheck.net) before posting here. Questions about interactive use of Bash are more likely to be on-topic on 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 and on MacOS; it is available on most modern operating systems, and has been ported to Windows 10.

A note regarding versions

As of January 2019, the most recent version of bash is 5.0, 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) uses version 3.2 by default 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. Questions tagged osx 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

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

    • 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)

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).

135523 questions
5373
votes
71 answers

How can I get the source directory of a Bash script from within the script itself?

How do I get the path of the directory in which a Bash script is located, inside that script? I want to use a Bash script as a launcher for another application. I want to change the working directory to the one where the Bash script is located, so I…
Jiaaro
  • 67,024
  • 38
  • 154
  • 182
3968
votes
36 answers

How can I check if a directory exists in a Bash shell script?

What command can be used to check if a directory exists or not, within a Bash shell script?
Grundlefleck
  • 115,195
  • 22
  • 89
  • 108
3527
votes
20 answers

How do I tell if a regular file does not exist in Bash?

I've used the following script to see if a file exists: #!/bin/bash FILE=$1 if [ -f $FILE ]; then echo "File $FILE exists." else echo "File $FILE does not exist." fi What's the correct syntax to use if I only want to check if the file…
Bill the Lizard
  • 369,957
  • 201
  • 546
  • 842
3061
votes
29 answers

How to concatenate string variables in Bash

In PHP, strings are concatenated together as follows: $foo = "Hello"; $foo .= " World"; Here, $foo becomes "Hello World". How is this accomplished in Bash?
Strawberry
  • 58,930
  • 53
  • 138
  • 190
2911
votes
26 answers

How to check if a string contains a substring in Bash

I have a string in Bash: string="My string" How can I test if it contains another string? if [ $string ?? 'foo' ]; then echo "It's there!" fi Where ?? is my unknown operator. Do I use echo and grep? if echo "$string" | grep 'foo'; then echo…
davidsheldon
  • 32,393
  • 4
  • 25
  • 27
2791
votes
23 answers

Echo newline in Bash prints literal \n

In Bash, tried this: echo -e "Hello,\nWorld!" But it doesn't print a newline, only \n. How can I make it print the newline? I'm using Ubuntu 11.04 (Natty Narwhal).
Sergey
  • 39,828
  • 24
  • 80
  • 122
2542
votes
18 answers

In the shell, what does " 2>&1 " mean?

In a Unix shell, if I want to combine stderr and stdout into the stdout stream for further manipulation, I can append the following on the end of my command: 2>&1 So, if I want to use head on the output from g++, I can do something like this: g++…
Tristan Havelick
  • 58,645
  • 19
  • 52
  • 64
2500
votes
39 answers

How can I check if a program exists from a Bash script?

How would I validate that a program exists, in a way that will either return an error and exit, or continue with the script? It seems like it should be easy, but it's been stumping me.
gregh
  • 30,059
  • 8
  • 27
  • 26
2341
votes
37 answers

Extract filename and extension in Bash

I want to get the filename (without extension) and the extension separately. The best solution I found so far is: NAME=`echo "$FILE" | cut -d'.' -f1` EXTENSION=`echo "$FILE" | cut -d'.' -f2` This is wrong because it doesn't work if the file name…
ibz
  • 38,044
  • 21
  • 65
  • 83
2301
votes
32 answers

How do I split a string on a delimiter in Bash?

I have this string stored in a variable: IN="bla@some.com;john@home.com" Now I would like to split the strings by ; delimiter so that I have: ADDR1="bla@some.com" ADDR2="john@home.com" I don't necessarily need the ADDR1 and ADDR2 variables. If…
stefanB
  • 69,149
  • 26
  • 113
  • 140
2162
votes
37 answers

How do I parse command line arguments in Bash?

Say, I have a script that gets called with this line: ./myscript -vfd ./foo/bar/someFile -o /fizz/someOtherFile or this one: ./myscript -v -f -d -o /fizz/someOtherFile ./foo/bar/someFile What's the accepted way of parsing this such that in each…
Lawrence Johnston
  • 58,608
  • 40
  • 113
  • 181
2098
votes
31 answers

How to change the output color of echo in Linux

I am trying to print a text in the terminal using echo command. I want to print the text in a red color. How can I do that?
satheesh.droid
  • 24,169
  • 8
  • 32
  • 33
1924
votes
14 answers

How do I set a variable to the output of a command in Bash?

I have a pretty simple script that is something like the following: #!/bin/bash VAR1="$1" MOREF='sudo run command against $VAR1 | grep name | cut -c7-' echo $MOREF When I run this script from the command line and pass it the arguments, I am not…
John
  • 19,653
  • 5
  • 20
  • 24
1841
votes
16 answers

How to reload .bashrc settings without logging out and back in again?

If I make changes to .bashrc, how do I reload it without logging out and back in?
Jed Daniels
  • 21,135
  • 5
  • 22
  • 24
1840
votes
37 answers

How to check if a variable is set in Bash?

How do I know if a variable is set in Bash? For example, how do I check if the user gave the first parameter to a function? function a { # if $1 is set ? }
prosseek
  • 155,475
  • 189
  • 518
  • 818
1
2 3
99 100