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
57
votes
14 answers

How to remove the last character from a bash grep output

COMPANY_NAME=`cat file.txt | grep "company_name" | cut -d '=' -f 2` outputs something like this "Abc Inc"; What I want to do is I want to remove the trailing ";" as well. How can i do that? I am a beginner to bash. Any thoughts or suggestions…
liv2hak
  • 12,597
  • 41
  • 127
  • 231
57
votes
7 answers

How to use `while read` (Bash) to read the last line in a file if there’s no newline at the end of the file?

Let’s say I have the following Bash script: while read SCRIPT_SOURCE_LINE; do echo "$SCRIPT_SOURCE_LINE" done I noticed that for files without a newline at the end, this will effectively skip the last line. I’ve searched around for a solution and…
Mathias Bynens
  • 130,201
  • 49
  • 208
  • 240
57
votes
6 answers

How to get a random string of 32 hexadecimal digits through command line?

I'd like to put together a command that will print out a string of 32 hexadecimal digits. I've got a Python script that works: python -c 'import random ; print "".join(map(lambda t: format(t, "02X"), [random.randrange(256) for x in…
Ana
  • 11,726
  • 5
  • 49
  • 101
57
votes
5 answers

How to UNCOMMENT a line that contains a specific string using Sed?

The lines in the file : -A INPUT -m state --state NEW -m tcp -p tcp --dport 2000 -j ACCEPT -A INPUT -m state --state NEW -m tcp -p tcp --dport 2001 -j ACCEPT -A INPUT -m state --state NEW -m tcp -p tcp --dport 2002 -j ACCEPT to comment out let's…
user3864928
57
votes
4 answers

How do I copy cookies from Chrome?

I am using bash to to POST to a website that requires that I be logged in first. So I need to send the request with login cookie. So I tried logging in and keeping the cookies, but it doesn't work because the site uses javascript to hash the…
jackcogdill
  • 4,343
  • 3
  • 24
  • 45
57
votes
4 answers

How do you print received cookie info to stdout with curl?

How do you print received cookie info to stdout with curl? According to the man pages if you use '-' as the file name for the -c --cookie-jar option it should print the cookie to stdout. The problem is I get an error: curl: option -: is…
Brian Yeh
  • 2,595
  • 3
  • 19
  • 30
57
votes
4 answers

Read JSON data in a shell script

In shell I have a requirement wherein I have to read the JSON response which is in the following format: { "Messages": [ { "Body": "172.16.1.42|/home/480/1234/5-12-2013/1234.toSort", "ReceiptHandle":…
user1305398
  • 3,111
  • 2
  • 22
  • 37
57
votes
4 answers

How to set a variable to current date and date-1 in linux?

I want to set the variable date-today to the current date, and date_dir to yesterday's date, both in the format yyyy-mm-dd. I am doing this: #!/bin/bash d=`date +%y%m%d%H%M%S` echo $d
cloudbud
  • 2,226
  • 1
  • 16
  • 30
57
votes
7 answers

How to make OS X to read .bash_profile not .profile file

I have read so many suggestions about, not putting your customization aka commands in ".profile" file. Rather, create a .bash_profile for yourself and add your alias and etc. But,when I open the new terminal, if there is only .bash_profile, OS X is…
cherryhitech
  • 1,761
  • 3
  • 15
  • 15
57
votes
7 answers

subtract days from a date in bash

I want to subtract "number of days" from a date in bash. I am trying something like this .. echo $dataset_date #output is 2013-08-07 echo $date_diff #output is 2 p_dataset_date=`$dataset_date --date="-$date_diff days" +%Y-%m-%d` # Getting…
Shivam Agrawal
  • 1,640
  • 4
  • 22
  • 38
57
votes
5 answers

Git Checkout Latest Tag

I'm writing a shell script and I'm looking to checkout the latest version of repo. Specifically I want to break this process apart into multiple steps. I want to save the repositories latest tag into a variable Print out Checking out version:…
BFTrick
  • 4,331
  • 5
  • 22
  • 28
57
votes
2 answers

How to use SED to find and replace URL strings with the "/" character in the targeted strings?

I'm attempting to use SED through OS X Terminal to perform a find and replace. Imagine I have this string littered throughout the text file: http://www.find.com/page And I want to replace it with this string: http://www.replace.com/page I'm having…
LearnWebCode
  • 1,121
  • 2
  • 11
  • 22
57
votes
3 answers

Bash convert epoch to date, showing wrong time

How come date is converting to wrong time? result=$(ls /path/to/file/File.*) #/path/to/file/File.1361234760790 currentIndexTime=${result##*.} echo "$currentIndexTime" #1361234760790 date -d@"$currentIndexTime" #Tue 24 Oct 45105 10:53:10 PM GMT
bobbyrne01
  • 5,464
  • 13
  • 60
  • 127
57
votes
1 answer

Running several scripts in parallel bash script

I have a bash script that contains other scripts inside that are run in series. However, it takes a decent amount of time to run them all. Is there a way to run these scripts in parallel to improve overall perfomance? They are independent of each…
Bdar
  • 713
  • 1
  • 5
  • 11
57
votes
1 answer

Meaning of "=~" operator in shell script

I came across a shell script where the code is for line in $LIST_ARRAY;do if [[ $LIST_ARRAY =~ $line ]] then echo "true" .... ... . What is the use of =~ in this case?
cc4re
  • 4,095
  • 3
  • 18
  • 27
1 2 3
99
100