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
82
votes
10 answers

Parse Date in Bash

How would you parse a date in bash, with separate fields (years, months, days, hours, minutes, seconds) into different variables? The date format is: YYYY-MM-DD hh:mm:ss
Steve
  • 829
  • 1
  • 6
  • 3
82
votes
10 answers

How can I make a bash command run periodically?

I want to execute a script and have it run a command every x minutes. Also any general advice on any resources for learning bash scripting could be really cool. I use Linux for my personal development work, so bash scripts are not totally foreign to…
jerome
  • 4,809
  • 13
  • 53
  • 70
82
votes
8 answers

-bash: __git_ps1: command not found

I tried to install Ruby 2.0. My command line urped and now looks like the following: -bash: __git_ps1: command not found [11:58:28][whatever@whatever ~]$ I have not a clue how to get rid of the __git_ps1: command not found error. I've searched my…
Joel Dehlin
  • 999
  • 1
  • 6
  • 9
82
votes
7 answers

Conversion hex string into ascii in bash command line

I have a lot of this kind of string and I want to find a command to convert it in ascii, I tried with echo -e and od, but it did not work. 0xA7.0x9B.0x46.0x8D.0x1E.0x52.0xA7.0x9B.0x7B.0x31.0xD2
Kerby82
  • 4,934
  • 14
  • 48
  • 74
82
votes
6 answers

bash echo number of lines of file given in a bash variable without the file name

I have the following three constructs in a bash script: NUMOFLINES=$(wc -l $JAVA_TAGS_FILE) echo $NUMOFLINES" lines" echo $(wc -l $JAVA_TAGS_FILE)" lines" echo "$(wc -l $JAVA_TAGS_FILE) lines" And they both produce identical output when the…
Marcus Junius Brutus
  • 26,087
  • 41
  • 189
  • 331
82
votes
5 answers

Wait for bash background jobs in script to be finished

To maximize CPU usage (I run things on a Debian Lenny in EC2) I have a simple script to launch jobs in parallel: #!/bin/bash for i in apache-200901*.log; do echo "Processing $i ..."; do_something_important; done & for i in apache-200902*.log; do…
mark
  • 6,308
  • 8
  • 46
  • 57
82
votes
13 answers

Capturing output of find . -print0 into a bash array

Using find . -print0 seems to be the only safe way of obtaining a list of files in bash due to the possibility of filenames containing spaces, newlines, quotation marks etc. However, I'm having a hard time actually making find's output useful within…
Idris
  • 1,887
  • 1
  • 14
  • 9
81
votes
4 answers

What are the error exit values for diff?

On the diff man-page I've found these exit values: 0 No differences were found. 1 Differences were found. >1 An error occurred. Are there different exit values above 1 for different errors?
sid_com
  • 24,137
  • 26
  • 96
  • 187
81
votes
2 answers

Test for empty string with X""

I know I can test for an empty string in Bash with -z like so: if [[ -z $myvar ]]; then do_stuff; fi but I see a lot of code written like: if [[ X"" = X"$myvar" ]]; then do_stuff; fi Is that method more portable? Is it just historical cruft from…
mgalgs
  • 15,671
  • 11
  • 61
  • 74
81
votes
14 answers

Python - Activate conda env through shell script

I am hoping to run a simple shell script to ease the management around some conda environments. Activating conda environments via conda activate in a linux os works fine in the shell but is problematic within a shell script. Could someone point me…
user9074332
  • 2,336
  • 2
  • 23
  • 39
81
votes
3 answers

Bash: split long string argument to multiple lines?

Given a command that takes a single long string argument like: mycommand -arg1 "very long string which does not fit on the screen" is it possible to somehow split it in a way similar to how separate arguments can be split with \. I tried: mycommand…
ccpizza
  • 28,968
  • 18
  • 162
  • 169
81
votes
4 answers

How can I loop over the output of a shell command?

I want to write a script that loops through the output (array possibly?) of a shell command, ps. Here is the command and the output: $ ps -ewo pid,cmd,etime | grep python | grep -v grep | grep -v sh 3089 python /var/www/atm_securit …
adic26
  • 997
  • 1
  • 6
  • 12
81
votes
10 answers

How can I split one text file into multiple *.txt files?

I got a text file file.txt (12 MB) containing: something1 something2 something3 something4 (...) Is there a way to split file.txt into 12 *.txt files, let’s say file2.txt, file3.txt, file4.txt, etc.?
Kris
  • 1,067
  • 2
  • 12
  • 15
81
votes
2 answers

Linux Terminal: typing feedback gone, line breaks not displayed

From time to time I have to run a command-line tool (a Python script) whose output seems to break my terminal. After the execution is finished, the typing feedback is gone (I can't see what I'm typing), and also line breaks are not displayed. This…
E.Z.
  • 6,393
  • 11
  • 42
  • 69
81
votes
5 answers

What is the difference between using `sh` and `source`?

What is the difference between sh and source? source: source filename [arguments] Read and execute commands from FILENAME and return. The pathnames in $PATH are used to find the directory containing FILENAME. If any ARGUMENTS are…
0x90
  • 39,472
  • 36
  • 165
  • 245