Home > Back-end >  How to get path from where shell file was run from Linux?
How to get path from where shell file was run from Linux?

Time:02-19

I have created a custom script for creating a file inside the directory. /mnt/c/Users/username/Documents/mkfile.sh (I am using the windows subsystem for Linux)

dir_str=$1
dir_arr=($(echo $dir_str | tr "[\\\/]" "\n"))
dir_path=""
file_name=""

for i in "${!dir_arr[@]}"
do 
  dirArrLen=${#dir_arr[@]}
  if [ $(($i 1)) -ge $dirArrLen ] 
  then
    sudo touch "${dir_path}/${dir_arr[$i]}"
    file_name=${dir_arr[$i]}
    # echo "${dir_path}/${dir_arr[$i]}"
  elif [ $(($i 1)) -eq 1 ]
  then
    # to avoid starting slash
    sudo mkdir "${dir_arr[$i]}"
    dir_path=${dir_arr[$i]}
    # echo $dir_path
  else
    sudo mkdir "${dir_path}/${dir_arr[$i]}"
    # echo "${dir_path}/${dir_arr[$i]}"
    dir_path="${dir_path}/${dir_arr[$i]}"
  fi
done
echo "File ${file_name} has been created successfully in ${dir_path}"

when this is executed inside the path(/mnt/c/Users/username/Documents/) where mkfile shell script file is present at now it creates a file successfully. ex:

Input :

/mnt/c/Users/username/Documents$./mkfile.sh hello/world/new.txt

Output: It creates a new.txt file inside like : /mnt/c/Users/username/Documents/hello/world/new.txt

File new.txt has been created successfully in hello/world

but when I move the file to the home directory add it to alias in ~/.bashrc file like(To make it as a custom shell command)

alias mkfile="~/mkfile.sh"

This shell script is not working(I think this is trying to create a file in the home directory instead from where it was called), ex:

username@DESKTOP-SELKMGP:/mnt/c/Users/username/Documents/$ mkfile hello/world/new.txt

does not create any directory/file inside documents.

Question:

Inside mkfile.sh file situated in the home directory is there any way to capture the path of the directory from where the command was entered,

ex:

Input :

/mnt/c/Users/username/Documents$ mkfile hello/world/new.txt

Expected : Inside ~/mkfile.sh situated in home directory I want to get: /mnt/c/Users/username/Documents/

I tried pwd but that outputs the home directory path instead of the path from where the command was entered and also realpath $0 did not work

CodePudding user response:

I understand what your problem is, I think you should set alias as below:

alias mkfile="~/mkfile.sh $(pwd)"

this command sent full path of where it was called to script as dir_str

try this one, I hope this helps.

  • Related