Bash – Pass command line arguments to bash script

bashscriptingshell

I am new to bash script programming.

I want to implement a bash script 'deploymLog', which accepts as input one string argument(name).

[root@localhost Desktop]# ./deploymLog.sh name

here I want to pass the string argument(name) through command line

As an initial step, I need to append the current timestamp along with this input string to a log file say Logone.txt in current directory in the below format:

[name]=[System time timestamp1]

How it is possible?

Best Answer

$> cat ./deploymLog.sh 
#!/bin/bash

name=$1
log_file="Logone.txt"

if [[ -n "$name" ]]; then
    echo "$1=$( date +%s )" >> ${log_file}
else
    echo "argument error"
fi

The first argument from a command line can be found with the positional parameter $1. [[ -n "$name" ]] tests to see if $name is not empty. date +%s returns the current timestamp in Unix time. The >> operator is used to write to a file by appending to the existing data in the file.

$> ./deploymLog.sh tt

$> cat Logone.txt 
tt=1329810941

$> ./deploymLog.sh rr

$> cat Logone.txt 
tt=1329810941
rr=1329810953

For more readable timestamp you could play with date arguments.

Related Question