Top 100 Bash Questions on Stack Overflow

Searches

1-10

  1. +4324 Get the source directory of a Bash script from within the script itself

    __file__ is the file itself, so to get the parent:

    # fully resolved
    pathlib.Path(__file__).parent
    os.path.abspath(os.path.join(__file__, os.path.pardir))
    
    # may still be relative
    pathlib.Path(__file__).parent.resolve()
    os.path.normpath(os.path.join(__file__, os.path.pardir))
    
  2. +2875 How do I tell if a regular file does not exist in Bash?

    Use os.path.exists() or pathlib.Path.exists(), or just try it as it’s EAFP than to LBYL.

  3. +2390 How to concatenate string variables in Bash

    Yes, this is not obvious in Bash. string1 + string2.

  4. +2027 How to check if a string contains a substring in Bash

    Also tricky…in Bash. Trivial in Python: substring in string.

  5. +1938 In the shell, what does ” 2>&1 ” mean?

    The syntax generally isn’t as obscure, and to do something like switching stdout and stderr, you don’t need to master crazy heiroglyphics like 3>&1- 1>&2- 2>&3-.

  6. +1902 `Echo newline in Bash prints literal \\n`_

    Escaping feels inconsistent in Bash, versus in Python where there is a clear distinction between repr()sentations of strings and presentation of them via print().

  7. +1819 How to check if a program exists from a Bash script?

    Try it, or shutil.which().

  8. +1801 Extract filename and extension in Bash

    os.path.splitext(), pathlib.PurePath.name, pathlib.PurePath.suffix

  9. +1692 How do I split a string on a delimiter in Bash?

  10. +1561 How do I parse command line arguments in Bash?

    argparse or DIY from sys.argv.

11-20

  1. +1414 How to count all the lines of code in a directory recursively?

  2. +1370 How to change the output color of echo in Linux

    Here it’s more about interacting with the terminal emulator, so you basically can do the same thing as Bash does. However, the escapes can be tricky a la the “how do I echo a newline” question above, while in Python it’s much more clear. At the most basic:

    print("\x1B[91mTHIS IS RED\x1B[0m")
    

    There are also cross-platform terminal color libraries like colorama which can make life easier too.

  3. +1364 How do I reload .bashrc without logging out and back in?

  4. +1336 How can I redirect and append both stdout and stderr to a file with Bash?

    When running a subprocess, you can combine the streams if you specify stderr=subprocess.STDOUT.

  5. +1295 How to set a variable to the output of a command in Bash?

    [command-line] [shell]

    Yes, this is also non-obvious in Bash.

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

    Read via input() and do whatever you want.

  7. +1242 How to check if a variable is set in Bash?

    Bash doesn’t

  8. +1235 How do I iterate over a range of numbers defined by variables in Bash?

    for n in range(x, y, z):

  9. +1202 Loop through an array of strings in Bash?

    for s in strings:

  10. +1097 Looping through the content of a file in Bash

    for line in open_file:

21-30

  1. +1061 Check existence of input argument in a Bash shell script

    argparse.

  2. +1048 Difference between sh and bash

    Vaguely similar to Python 2/3; sometimes you can pretend they’re the same, but you need to know the difference when it matters.

  3. +1030 How to convert a string to lower case in Bash?

    str.lower()

  4. +1020 Make a Bash alias that takes a parameter?

    A Bash alias is a canned command, you’d need to do this with a function.

  5. +937 YYYY-MM-DD format date in shell script

    The strftime specifications are the same as they’re from C, and in Python you use them with datetime.datetime.strftime().

  6. +920 What is the preferred Bash shebang?

    A good question for Python as well, there’s #!/usr/bin/env python, or …``python3``…

  7. +902 echo that outputs to stderr

    import sys
    
    print(..., file=sys.stderr)
    
  8. +879 How to count lines in a document?

    There are a few methods involving iterating over an open file and incrementing, and you can look at other Stack Overflow questions for more discussion. Notably, if this is a bottleneck, you can easily call out to wc.

  9. +851 How to pipe stderr, and not stdout?

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

    [git] [shell] [ssh]

41-50

  1. +759 How to trim whitespace from a Bash variable?

    str.strip()

  2. +755 How to declare and use boolean variables in shell script?

    This is non-obvious because there isn’t a boolean type in shell. There are also myriad ways to get it wrong that “look” nice if you view the question.

  3. +749 How can I exclude all “permission denied” messages from “find”? [error-handling] [file-permissions] [find]

  4. +724 How to permanently set $PATH on Linux/Unix? [linux] [path] [unix] [zsh]

  5. +705 What are the special dollar sign shell variables?

    Python has a cleaner return semantics from calls, so it doesn’t need magic variables like $?. That said, Python has _ which can be useful in interactive contexts.

  6. +698 Get current directory name (without full path) in a Bash script [shell]

  7. +682 Given two directory trees, how can I find out which files differ? [diff] [linux] [shell] [unix]

  8. +681 Parsing JSON with Unix tools

    json

  9. +672 Redirect all output to file [io-redirection] [linux]

  10. +665 Propagate all arguments in a bash shell script [command-line-arguments]

51-60

  1. +646 Add a new element to an array without specifying the index in Bash [arrays]
  2. +640 How do I clear/delete the current line in terminal? [terminal]
  3. +638 Count number of lines in a git repository [git] [line-count] [shell]
  4. +633 Read a file line by line assigning the value to a variable
  5. +630 How to ‘grep’ a continuous stream? [grep] [linux] [shell] [tail]
  6. +628 How can I write a heredoc to a file in Bash script? [heredoc]
  7. +620 How do I remove all .pyc files from a project?
  8. +610 Add line break to ‘git commit -m’ from the command line [git] [shell]
  9. +604 How to use double or single brackets, parentheses, curly braces [syntax]
  10. +600 Redirect stderr and stdout in Bash [pipe] [redirect] [shell]
  11. +595 In bash, how can I check if a string begins with some value? [comparison] [string]
  12. +592 Extract substring in Bash [shell] [string] [substring]
  13. +588 How to do a recursive find/replace of a string with awk or sed? [awk] [replace] [sed]
  14. +584 Check number of arguments passed to a Bash script [parameter-passing]
  15. +579 Replace one substring for another string in shell script [shell]
  16. +579 Reliable way for a Bash script to get the full path to itself [path]
  17. +577 How to call shell script from another shell script? [shell]
  18. +559 Check if pull needed in Git [git] [shell]
  19. +551 In a Bash script, how can I exit the entire script if a certain condition occurs? [exit] [exit-code] [scripting]
  20. +545 Find and kill a process in one line using bash and regex [awk] [regex] [terminal]
  21. +542 How do I pause my shell script for a second before continuing? [shell] [terminal] [unix]
  22. +538 Syntax for a single-line Bash infinite while loop [loops] [while-loop]
  23. +537 How to determine the current shell I’m working on? [csh] [shell] [tcsh] [unix]
  24. +536 When do we need curly braces around shell variables? [curly-braces] [shell] [syntax]
  25. +536 Why is whitespace sometimes needed around metacharacters? [shell] [syntax] [syntax-error]
  26. +522 How do I compare two string variables in an ‘if’ statement in Bash? [if-statement] [scripting]
  27. +519 How to do a logical OR operation in Shell Scripting [if-statement] [sh] [unix]
  28. +517 What does set -e mean in a bash script? [linux] [sh] [shell]
  29. +514 sudo echo “something” >> /etc/privilegedFile doesn’t work [permissions] [scripting] [shell] [sudo]
  30. +513 Assigning default values to shell variables with a single command in bash [shell]
  31. +511 Automatic exit from bash shell script on error [exit] [shell]
  32. +507 Split string into an array in Bash [arrays] [split]
  33. +503 How do I know the script file name in a Bash script? [linux] [scripting] [shell]
  34. +503 How do I prompt a user for confirmation in bash script?
  35. +499 Get current time in seconds since the Epoch on Linux, Bash [datetime] [linux]
  36. +497 Capturing multiple line output into a Bash variable [variables]
  37. +495 How do I test if a variable is a number in Bash? [linux] [shell]
  38. +490 How to kill all processes with a given partial name? [linux] [posix]
  39. +485 How to run a shell script on a Unix console or Mac terminal? [linux] [macos] [shell] [unix]
  40. +482 How does “cat << EOF” work in bash? [heredoc] [linux] [scripting]
  41. +480 How do I get cURL to not show the progress bar? [curl] [linux] [scripting] [unix]
  42. +470 How to pass all arguments passed to my bash script to a function of mine? [function] [parameter-passing]
  43. +468 Bash tool to get nth line from a file [awk] [sed] [shell] [unix]
  44. +464 How to wait in bash for several subprocesses to finish and return exit code !=0 when any subprocess ends with code !=0? [process] [wait]
  45. +464 What’s a concise way to check that environment variables are set in a Unix shell script? [shell] [unix]
  46. +463 How do I write stderr to a file while using “tee” with a pipe? [linux] [unix]
  47. +460 How can I add numbers in a bash script [mathematical-expressions]
  48. +459 How can I remove the first line of a text file using bash/sed script? [scripting] [sed]
  49. +457 Find and Replace Inside a Text File from a Bash Command [ironpython] [replace] [scripting] [ssh]
  50. +455 How to define hash tables in Bash?
[associative-array] [dictionary] [hashtable]