2011-01-14 125 views
2

我正在嘗試編寫一個bash腳本來更改目錄,然後在新的工作目錄中運行現有的腳本。快速bash腳本在指定文件夾中運行腳本?

這是我到目前爲止有:

#!/bin/bash 
cd /path/to/a/folder 
./scriptname 

腳本名稱是存在於/路徑中的可執行文件/到/一個/文件夾 - 和(不用說了),我確實有運行權限腳本。

然而,當我運行這個頭腦麻木簡單的腳本(上圖),我得到的迴應:

腳本名:沒有這樣的文件或目錄

我在想什麼?這些命令在CLI中輸入時按預期工作,因此我無法解釋錯誤消息。我該如何解決?

+0

嗯,通過許多(不同的)反應來判斷 - 包括一兩個肯定會過度的反應 - 我不禁會奇怪 - 當然,必須有一種簡單的方法來轉換文件夾並運行腳本夾? – skyeagle 2011-01-14 15:21:30

+0

您尚未將腳本複製到該文件夾​​。 ./scriptname表示腳本位於該文件夾中,而不是這種情況。通過給出正確的路徑來調用腳本。 – BZ1 2011-01-17 04:23:35

+0

您可以添加以下內容作爲您想要的別名嗎? 「bash /path/to/script/script.sh」 – Hemm 2013-04-21 01:10:20

回答

3
cd /path/to/a/folder 
pwd 
ls 
./scriptname 

which'll告訴你什麼是它認爲它在做什麼。

4

看着你的腳本讓我覺得你想要啓動腳本的腳本位於最初的目錄。由於您在執行之前更改了目錄,因此無法使用。

我建議以下修改後的腳本:

#!/bin/bash 
SCRIPT_DIR=$PWD 
cd /path/to/a/folder 
$SCRIPT_DIR/scriptname 
+0

不,你一定誤解了我。我想在/ path/to/a /文件夾中運行腳本(這就是爲什麼我首先要「cd/path/to/a/folder」)。 – skyeagle 2011-01-14 15:15:20

1

我通常在我的有用腳本目錄是這樣的:

#!/bin/bash 

# Provide usage information if not arguments were supplied 
if [[ "$#" -le 0 ]]; then 
     echo "Usage: $0 <executable> [<argument>...]" >&2 

     exit 1 
fi 

# Get the executable by removing the last slash and anything before it 
X="${1##*/}" 

# Get the directory by removing the executable name 
D="${1%$X}" 

# Check if the directory exists 
if [[ -d "$D" ]]; then 
     # If it does, cd into it 
     cd "$D" 
else 
     if [[ "$D" ]]; then 
       # Complain if a directory was specified, but does not exist 
       echo "Directory '$D' does not exist" >&2 

       exit 1 
     fi 
fi 

# Check if the executable is, well, executable 
if [[ -x "$X" ]]; then 
     # Run the executable in its directory with the supplied arguments 
     exec ./"$X" "${@:2}" 
else 
     # Complain if the executable is not a valid 
     echo "Executable '$X' does not exist in '$D'" >&2 

     exit 1 
fi 

用法:在這些條件下,這樣的錯誤消息

$ cdexec 
Usage: /home/archon/bin/cdexec <executable> [<argument>...] 
$ cdexec /bin/ls ls 
ls 
$ cdexec /bin/xxx/ls ls 
Directory '/bin/xxx/' does not exist 
$ cdexec /ls ls 
Executable 'ls' does not exist in '/' 
0

一個來源是一個破碎的符號鏈接。

但是,你說腳本在從命令行運行時工作。我也會檢查目錄是否是一個符合你所期望的以外的符號鏈接。

如果您在腳本中使用完整路徑而不是使用cd調用它,它會工作嗎?

#!/bin/bash 
/path/to/a/folder/scriptname 

從命令行調用這種方式怎麼樣?