EzDevInfo.com

bash interview questions

Top bash frequently asked interview questions

How do I tell if a regular file does not exist in bash?

I've used the following script to see if a file exists:

#!/bin/bash
FILE=$1

if [ -f $FILE ];
then
   echo "File $FILE exists."
else
   echo "File $FILE does not exist."
fi

What's the correct syntax to use if I only want to check if the file does not exist?

#!/bin/bash
FILE=$1

if [ $FILE does not exist ];
then
   echo "File $FILE does not exist."
fi

Source: (StackOverflow)

Setting environment variables in OS X?

What is the proper way to modify environment variables like PATH in OSX? I've looked on Google a little bit and found 3 different files to edit:

  • /etc/paths
  • ~/.profile
  • ~/.tcshrc

I don't even have some of these files, and I'm pretty sure that .tcshrc is wrong, since OSX uses bash now. Anybody have any idea where these variables, especially PATH, are defined?

Edit: I'm running OS X 10.5


Source: (StackOverflow)

Advertisements

How to pipe stderr, and not stdout?

I have a program that writes information to stdout and stderr, and I need to grep through what's coming to stderr, while disregarding stdout.

I can of course do it in 2 steps:

command > /dev/null 2> temp.file
grep 'something' temp.file

but I would prefer to be able to do tis without temp files. Any smart piping trick?


Source: (StackOverflow)

How to check if a variable is set in Bash?

How do I know if a variable is set in Bash?

For example, how do I check if the user gave the first parameter to a function?

function a {
    ?? if $1 is set
}

Source: (StackOverflow)

Can a Bash script tell what directory it's stored in?

How do I get the path of the directory in which a Bash script is located FROM that Bash script?

For instance, let's say I want to use a Bash script as a launcher for another application. I want to change the working directory to the one where the Bash script is located, so I can operate on the files in that directory, like so:

$ ./application

Source: (StackOverflow)

String contains in Bash

Using Bash, I have a string:

string = "My string"

How can I test if it contains another string?

if [ $string ?? 'foo' ]; then
  echo "It's there!"
fi

Where ?? is my unknown operator. Do I use echo and grep?

if echo "$string" | grep 'foo'; then
  echo "It's there!"
fi

That looks a bit clumsy.


Source: (StackOverflow)

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 can I replace either of the range endpoints with a variable? This doesn't work:

END=5
for i in {1..$END}; do echo $i; done

Which prints:

{1..5}


Source: (StackOverflow)

How to set a variable equal to the output from a command in Bash?

I am working on a simple scripting project for work that involves the use of Bash. I have a pretty simple script that is something like the following:

#!/bin/bash

VAR1="$1"
VAR2="$2"

MOREF='sudo run command against $VAR1 | grep name | cut -c7-'

echo $MOREF

When I run this script from the command line and pass it the arguments, I am not getting any output. However, when I run the commands contained within the $MOREF variable, I am able to get output. I would like to know how one can take the results of a command that needs to be run within a script, save it to a variable, and then output that variable on the screen?


Source: (StackOverflow)

Why is whitespace sometimes needed around metacharacters?

A few months ago I tattooed a fork bomb on my arm, and I skipped the whitespaces, because I think it looks nicer without them. But to my dismay, sometimes (not always) when I run it in a shell it doesn't start a fork bomb, but it just gives a syntax error.

bash: syntax error near unexpected token `{:'

Yesterday it happened when I tried to run it in a friend's Bash shell, and then I added the whitespace and it suddenly worked, :(){ :|:& };: instead of :(){:|:&};:

Does the whitespace matter; have I tattooed a syntax error on my arm?!

It seems to always work in zsh, but not in Bash.

A related question does not explain anything about the whitespaces, which really is my question; Why is the whitespace needed for Bash to be able to parse it correctly?

Off-topic update: I patched the tattoo by saying that there is a whitespace inbetween every character, which makes the code parsable again.

: ( ) { : | : & } ; :

Tattoo


Source: (StackOverflow)

How do I split a string on a delimiter in Bash?

How do I split a string based on a delimiter in Bash?

I have this string stored in a variable:

IN="bla@some.com;john@home.com"

Now I would like to split the strings by ; delimiter so that I have:

ADDR1="bla@some.com"
ADDR2="john@home.com"

I don't necessarily need the ADDR1 and ADDR2 variables. If they are elements of an array that's even better.


After suggestions from the answers below, I ended up with the following which is what I was after:

#!/usr/bin/env bash

IN="bla@some.com;john@home.com"

arr=$(echo $IN | tr ";" "\n")

for x in $arr
do
    echo "> [$x]"
done

Output:

> [bla@some.com]
> [john@home.com]

There was a solution involving setting Internal_field_separator (IFS) to ;. I am not sure what happened with that answer, how do you reset IFS back to default?

RE: IFS solution, I tried this and it works, I keep the old IFS and then restore it:

IN="bla@some.com;john@home.com"

OIFS=$IFS
IFS=';'
arr2=$IN
for x in $arr2
do
    echo "> [$x]"
done

IFS=$OIFS

BTW, when I tried

arr2=($IN) 

I only got the first string when printing it in loop, without brackets around $IN it works.


Source: (StackOverflow)

Extract filename and extension in Bash

I want to get the filename (without extension) and the extension separately.

The best solution I found so far is:

NAME=`echo "$FILE" | cut -d'.' -f1`
EXTENSION=`echo "$FILE" | cut -d'.' -f2`

This is wrong because it doesn't work if the file name contains multiple "." characters. If, let's say, I have a.b.js it will consider a and b.js, instead of a.b and js.

It can be easily done in Python with

file, ext = os.path.splitext(path)

but I'd prefer not to fire a Python interpreter just for this, if possible.

Any better ideas?


Source: (StackOverflow)

In the shell, what does " 2>&1 " mean?

In a Unix shell, if I want to combine stderr and stdout into the stdout stream for further manipulation, I can append the following on the end of my command:

2>&1

So, if I want to use "head" on the output from g++, I can do something like this:

g++ lots_of_errors 2>&1 | head

so I can see only the first few errors.

I always have trouble remembering this, and I constantly have to go look it up, and it is mainly because I don't fully understand the syntax of this particular trick. Can someone break this up and explain character by character what "2>&1" means?


Source: (StackOverflow)

How do I parse command line arguments in bash?

Say, I have a script that gets called with this line:

./myscript -vfd ./foo/bar/someFile -o /fizz/someOtherFile

or this one:

./myscript -v -f -d -o /fizz/someOtherFile ./foo/bar/someFile 

What's the accepted way of parsing this such that in each case (or some combination of the two) $v, $f, and $d will all be set to true and $outFile will be equal to /fizz/someOtherFile ?


Source: (StackOverflow)

How to output MySQL query results in CSV format?

Is there an easy way to run a MySQL query from the Linux command line and output the results in CSV format?

Here's what I'm doing now:

mysql -u uid -ppwd -D dbname << EOQ | sed -e 's/        /,/g' | tee list.csv
select id, concat("\"",name,"\"") as name
from students
EOQ

It gets messy when there are a lot of columns that need to be surrounded by quotes, or if there are quotes in the results that need to be escaped.


Source: (StackOverflow)

Check if a program exists from a Bash script

How would I validate that a program exists?

Which would then either return an error and exit or continue with the script?

It seems like it should be easy, but it's been stumping me.


Source: (StackOverflow)