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
73
votes
3 answers

Bash scripting, multiple conditions in while loop

I'm trying to get a simple while loop working in bash that uses two conditions, but after trying many different syntax from various forums, I can't stop throwing an error. Here is what I have: while [ $stats -gt 300 ] -o [ $stats -eq 0 ] I have…
jake9115
  • 3,964
  • 12
  • 49
  • 78
73
votes
7 answers

Retry a Bash command with timeout

How to retry a bash command until its status is ok or until a timeout is reached? My best shot (I'm looking for something simpler): NEXT_WAIT_TIME=0 COMMAND_STATUS=1 until [ $COMMAND_STATUS -eq 0 || $NEXT_WAIT_TIME -eq 4 ]; do command …
Philippe Blayo
  • 10,610
  • 14
  • 48
  • 65
73
votes
9 answers

How to quickly find all git repos under a directory

Update: The title of this question is misleading. Apologies. In the sample code below, however, there is git pull. This is the purpose: to update a tree of git repos. No need to list them. I show a bash script, but that language does not have good…
Mike Slinn
  • 7,705
  • 5
  • 51
  • 85
72
votes
3 answers

Date command does not follow Linux specifications (Mac OS X Lion)

I have been developing a script on my linux box for quite some time, and wanted to run it on my Mac as well. I thought that the functions on the Mac were the same as the functions on linux, but today I realized it was wrong. I knew that fewer…
Kaushik Shankar
  • 5,491
  • 4
  • 30
  • 36
72
votes
8 answers

self-deleting shell script

I've looked around for an answer to this one but couldn't find one. I have written a simple script that does initial server settings and I'd like it to remove/unlink itself from the root directory on completion. I've tried a number of solutions i…
RFH
  • 723
  • 1
  • 5
  • 5
72
votes
4 answers

What is the meaning of a question mark in bash variable parameter expansion as in ${var?}?

What is the meaning of a bash variable used like this: ${Server?}
Kai
  • 2,145
  • 1
  • 20
  • 35
72
votes
8 answers

Start script after another one (already running) finishes

So I have a process running, and it will take several hours to complete. I would like to start another process right after that one finishes, automatically. Notice that I can't add a call to the second script in the first one, neither create another…
skd
  • 1,865
  • 1
  • 21
  • 29
72
votes
7 answers

Variables in bash seq replacement ({1..10})

Is it possible to do something like this: start=1 end=10 echo {$start..$end} # Ouput: {1..10} # Expected: 1 2 3 ... 10 (echo {1..10})
Tyilo
  • 28,998
  • 40
  • 113
  • 198
72
votes
5 answers

Windows 10 Bash (Ubuntu) - How to scroll up?

I have bash installed on my W10 laptop, but one thing that is very frustrating is I can not scroll up. Does anyone know of a way to enable scrolling with the mouse wheel? I could not find anything after many google searches. Context: If I compile…
kebab-case
  • 1,732
  • 1
  • 13
  • 24
72
votes
2 answers

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" How does that work?

I need to get the path of the script. I can do that using pwd if I am already in the same directory, I searched online and I found this DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" But I don't know how to use that.
Alex Bloomberg
  • 855
  • 1
  • 7
  • 14
72
votes
6 answers

docker exec is not working in cron

I have pretty simple command which is working fine standalone as a command or bash script but not when I put it in crontab 40 05 * * * bash /root/scripts/direct.sh >> /root/cron.log which has following…
user555
  • 1,489
  • 2
  • 15
  • 28
72
votes
1 answer

Matplotlib plots aren't shown when running file from bash terminal

Plots are normally shown when I run files from the ipython shell or from an ipython notebook, but they don't show up when I run the file from a bash terminal -- everything else works fine when is run from a bash terminal. Sample python script…
drake
  • 1,012
  • 2
  • 9
  • 17
72
votes
11 answers

How to get ip address of a server on Centos 7 in bash

Previously I used the following command in bash to find the main ip of my server ipaddr=$(/sbin/ifconfig|grep inet|head -1|sed 's/\:/ /'|awk '{print $3}' | grep -v '127.0.0.1') But in centos7 it no longer works since ifconfig isn't available and…
user2650277
  • 6,289
  • 17
  • 63
  • 132
72
votes
8 answers

Mac OS X 10.9 - setting permanent environment variables

How do I set a permanent environment variable (i.e. one that does not need exporting every time I start a new Terminal session) in Mac OS X 10.9? I've found a number of answers about modifying my .bash_profile and .profile, however neither of these…
danw
  • 1,608
  • 4
  • 29
  • 48
72
votes
43 answers

Hidden features of Bash

Shell scripts are often used as glue, for automation and simple one-off tasks. What are some of your favorite "hidden" features of the Bash shell/scripting language? One feature per answer Give an example and short description of the feature, not…
Patrick
  • 90,362
  • 11
  • 51
  • 61
1 2 3
99
100