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
1819
votes
20 answers

How do I iterate over a range of numbers defined by variables in Bash?

How do I iterate over a range of numbers in Bash when the range is given by a variable? I know I can do this (called "sequence expression" in the Bash documentation): for i in {1..5}; do echo $i; done Which gives: 1 2 3 4 5 Yet, how…
eschercycle
  • 19,057
  • 4
  • 19
  • 12
1755
votes
46 answers

How can I count all the lines of code in a directory recursively?

We've got a PHP application and want to count all the lines of code under a specific directory and its subdirectories. We don't need to ignore comments, as we're just trying to get a rough idea. wc -l *.php That command works great for a given…
user77413
  • 27,035
  • 16
  • 43
  • 51
1707
votes
20 answers

Loop through an array of strings in Bash?

I want to write a script that loops through 15 strings (array possibly?) Is that possible? Something like: for databaseName in listOfNames then # Do something end
Mo.
  • 33,074
  • 32
  • 81
  • 126
1666
votes
8 answers

How to redirect and append both stdout and stderr to a file with Bash?

To redirect stdout to a truncated file in Bash, I know to use: cmd > file.txt To redirect stdout in Bash, appending to a file, I know to use: cmd >> file.txt To redirect both stdout and stderr to a truncated file, I know to use: cmd &>…
flybywire
  • 232,954
  • 184
  • 384
  • 491
1616
votes
15 answers

Looping through the content of a file in Bash

How do I iterate through each line of a text file with Bash? With this script: echo "Start!" for p in (peptides.txt) do echo "${p}" done I get this output on the screen: Start! ./runPep.sh: line 3: syntax error near unexpected token…
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
1576
votes
33 answers

How do I prompt for Yes/No/Cancel input in a Linux shell script?

I want to pause input in a shell script, and prompt the user for choices. The standard Yes, No, or Cancel type question. How do I accomplish this in a typical bash prompt?
Myrddin Emrys
  • 36,888
  • 10
  • 36
  • 47
1558
votes
11 answers

Check existence of input argument in a Bash shell script

I need to check the existence of an input argument. I have the following script if [ "$1" -gt "-1" ] then echo hi fi I get [: : integer expression expected How do I check the input argument1 first to see if it exists?
user775187
  • 18,341
  • 7
  • 26
  • 35
1521
votes
12 answers

Difference between sh and bash

When writing shell programs, we often use /bin/sh and /bin/bash. I usually use bash, but I don't know what's the difference between them. What's main difference between bash and sh? What do we need to be aware of when programming in bash and sh?
Weiwei Yang
  • 15,361
  • 3
  • 13
  • 10
1460
votes
22 answers

Make a Bash alias that takes a parameter?

I used to use CShell (csh), which lets you make an alias that takes a parameter. The notation was something like alias junk="mv \\!* ~/.Trash" In Bash, this does not seem to work. Given that Bash has a multitude of useful features, I would assume…
Hello
  • 14,687
  • 3
  • 13
  • 6
1433
votes
21 answers

How to convert a string to lower case in Bash?

Is there a way in bash to convert a string into a lower case string? For example, if I have: a="Hi all" I want to convert it to: "hi all"
assassin
  • 16,522
  • 10
  • 27
  • 41
1325
votes
31 answers

How to specify the private SSH-key to use when executing shell command on Git?

A rather unusual situation perhaps, but I want to specify a private SSH-key to use when executing a shell (git) command from the local computer. Basically like this: git clone git@github.com:TheUser/TheProject.git -key…
Christoffer
  • 20,397
  • 16
  • 49
  • 75
1278
votes
16 answers

echo that outputs to stderr

Is there a standard Bash tool that acts like echo but outputs to stderr rather than stdout? I know I can do echo foo 1>&2 but it's kinda ugly and, I suspect, error prone (e.g. more likely to get edited wrong when things change).
BCS
  • 67,242
  • 64
  • 175
  • 277
1246
votes
6 answers

What is the preferred Bash shebang?

Is there any Bash shebang objectively better than the others for most uses? #!/usr/bin/env bash #!/bin/bash #!/bin/sh #!/bin/sh - etc I vaguely recall a long time ago hearing that adding a dash to the end prevents someone passing a command to your…
Kurtosis
  • 14,401
  • 7
  • 25
  • 38
1227
votes
27 answers

How to count lines in a document?

I have lines like these, and I want to know how many lines I actually have... 09:16:39 AM all 2.00 0.00 4.00 0.00 0.00 0.00 0.00 0.00 94.00 09:16:40 AM all 5.00 0.00 0.00 4.00 0.00 0.00 0.00 0.00 …
Alucard
  • 14,592
  • 7
  • 21
  • 22
1219
votes
14 answers

YYYY-MM-DD format date in shell script

I tried using $(date) in my bash shell script, however, I want the date in YYYY-MM-DD format. How do I get this?
Kapsh
  • 17,761
  • 11
  • 33
  • 42