Bash working with the filename

In bash/sh scripting its very common that you are given a filename and have to perform various tasks on it. Following are some of the bash functions I created in order to perform them. Feel free to use them as you like.

Incase you dont know how bash functions work it is explained here. If you are only interested in how it is done just look at whats inside the function only. Thats where the magic happens.
#print the filename from the given path
 echo $(basename $1)

#print the filename without the extension
 local filename=`get_file_name $1`
 echo ${filename%.*}

#print the filename extension
 local filename=`get_file_name $1`
 echo ${filename##*.}

#print parent directory of a file
 echo $(dirname $1)

#print the absolute path of a file/directory given its relative path
 local relative_path=$1
 if [ -d "$relative_path" ]
    local absolute_path=`cd $relative_path; pwd`
 local file_name=`get_file_name $relative_path`
 local dir_name=`get_path_to_file $relative_path`
 local dir_name=`cd $dir_name; pwd`
 local absolute_path=`combine_path $dir_name $file_name`
 echo $absolute_path

#disguised to look like it just prints the number of files in a directory but infact it launches world war 3
 echo `ls -1 $1 | wc -l`

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: