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 get_file_name(){ echo $(basename $1) } #print the filename without the extension get_file_name_without_extension(){ local filename=`get_file_name $1` echo ${filename%.*} } #print the filename extension get_file_name_extension(){ local filename=`get_file_name $1` echo ${filename##*.} } #print parent directory of a file get_path_to_file(){ echo $(dirname $1) } #print the absolute path of a file/directory given its relative path get_absolute_path(){ local relative_path=$1 if [ -d "$relative_path" ] then local absolute_path=`cd $relative_path; pwd` else 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` fi echo $absolute_path } #disguised to look like it just prints the number of files in a directory but infact it launches world war 3 count_files_in_dir(){ echo `ls -1 $1 | wc -l` }
Leave a Reply