shell脚本与文件的相对位置

shell脚本与文件的相对位置

我对 Linux 中的 shell 脚本或命令几乎一无所知

我有一个名为projectx

projectX恰好在users/hardik/desktop/projectx

我创建了一个 shell 脚本start.sh。这是shell脚本的内容

echo "Starting typescript build in new terminal.."

osascript -e 'tell application "Terminal" to do script "npm run build"' 

sleep 3

echo "Starting firebase functions...."

osascript -e 'tell application "Terminal" to do script "firebase emulators:start --only functions"'


echo "Process compelete.. Check if there were two terminals window open"

现在这有效,但在这里说

osascript -e 'tell application "Terminal" to do script "npm run build"'

它在根目录中运行,因此给出以下错误

ENOENT:没有那个文件或目录,打开/Users/hardik/package.json

我怎样才能让它在相对路径中执行start.sh

更新:我尝试了这些但没有用

cd "$(dirname $(readlink -f "$0"))"
echo "Starting typescript build in new terminal.."
osascript -e 'tell application "Terminal" to do script "npm run watch:scss"' 
osascript -e 'tell application "Terminal" to do script "npm run watch"'
echo "Process compelete.. Check if there were two terminals window open"

这就是上面记录的内容

readlink: illegal option -- f
usage: readlink [-n] [file ...]
usage: dirname path
Starting typescript build in new terminal..
tab 1 of window id 1579
tab 1 of window id 1580

下面的代码片段也不起作用

cd -P -- "${0%/*}" || exit
echo "Starting typescript build in new terminal.."
osascript -e 'tell application "Terminal" to do script "npm run watch:scss"' 
osascript -e 'tell application "Terminal" to do script "npm run watch"'
echo "Process compelete.. Check if there were two terminals window open"

同样的错误

答案1

您可以在脚本中添加 cd -P -- "${0%/*}" || exitcd -P -- "$(dirname -- "$0")" || exit 以跳转到脚本所在的目录。

$0是一个内置变量保存给解释器的脚本路径(如果在 中查找脚本,则通常是绝对路径$PATH)。

${0%/*}构造使用 shell 的内置字符串操作从末尾删除变量匹配的最短位/*,这样您就只剩下目录名称(只要$0包含至少一个/字符,通常是这种情况,就可以工作)。

答案2

我不知道这在 MacOS 下是否有效;它在Linux下是这样的:

#! /bin/bash
  
arg1="$(awk 'BEGIN { RS="\0" }; NR==2 { print $0 "x"; exit; }' /proc/$$/cmdline; echo x)"
arg1="${arg1%x}"

if [[ $arg1 =~ / ]]; then
    # path contains at least one /
    dir_rel_path="${arg1%/*}"
    cd "$dir_rel_path"
fi

echo "$PWD"

相关内容