我創建了一個自定義腳本,用于在目錄中創建檔案。/mnt/c/Users/username/Documents/mkfile.sh(我使用的是 Linux 的 windows 子系統)
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}"
當這在路徑(/mnt/c/Users/username/Documents/)內執行時,mkfile shell 腳本檔案現在存在,它會成功創建一個檔案。前任:
輸入 :
/mnt/c/Users/username/Documents$./mkfile.sh hello/world/new.txt
輸出: 它在里面創建一個 new.txt 檔案,如:/mnt/c/Users/username/Documents/hello/world/new.txt
File new.txt has been created successfully in hello/world
但是當我將檔案移動到主目錄時,將其添加到~/.bashrc檔案中的別名中(使其成為自定義 shell 命令)
alias mkfile="~/mkfile.sh"
這個shell腳本不作業(我認為這是試圖在主目錄中創建一個檔案,而不是從它被呼叫的位置),例如:
username@DESKTOP-SELKMGP:/mnt/c/Users/username/Documents/$ mkfile hello/world/new.txt
不會在檔案中創建任何目錄/檔案。
題:
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
uj5u.com熱心網友回復:
我了解您的問題是什么,我認為您應該將別名設定如下:
alias mkfile="~/mkfile.sh $(pwd)"
此命令將呼叫腳本的位置的完整路徑發送為dir_str
試試這個,我希望這會有所幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/427339.html
下一篇:重寫規則不適用
