执行chmod后,Bash脚本执行突然停止

时间:2014-09-25 09:56:40

标签: linux bash

我正在编写一个bash脚本来自动化我们公司的服务器部署过程。在这里我创建了一个名为dir_check的函数,用于检查某个目录是否在某个路径中可用。如果目录不可用,则函数会检查路径中的写入权限,以及在执行代码段后是否有写入权限。

        echo "Changing the permission to writable"
        exec sudo chmod 775 $1 -R
        exec sudo chown $USER:$USER -R

但是在执行chmod之后脚本终止了。它成功更改了权限,但执行被停止,没有任何错误或提示。任何人都可以为我提供答案。提前致谢。整个代码如下所示

#!/bin/bash -x

# Author: Sithum Nissanka
# Date: 25/09/2014
# Version: 1.0
# Script performs necessary steps to setup a linux environment for ######.

echo -e "Which environment are you setting up?"

function setup_server {
    echo "Path to the server archive:"
    read archive_path
        if [ $(($1)) -eq 2 ]; then
        echo "Uploading file to the user home in the remote server..."
        exec scp $archive_path $3@$2:
    else
        echo "Path to extract:"
        read extraction_path
        echo "Directory to extract:"
        read extraction_dir
        dir_check $extraction_path $extraction_dir 
    fi
}

function dir_check {
    echo "Checking for the directory"
    if [ ! -d "$2" ]; then
        echo "Checking permission for creating directory"
        if [ ! -w "$1" ]; then
            echo "Changing the permission to writable"
            exec sudo chmod 775 $1 -R
#           exec sudo chown $USER:$USER -R
        fi
        echo "Creating the directory $2"
        exec mkdir -p "$1/$2"
        exec ls -al $1
    fi
}

    echo -e "[1] local \n[2] remote"
    echo -n "Select your environment: "
    read env

    if [ $((env)) -eq 2 ]; then
        echo -n "Host:"
        read host
        echo -n "User:"
        read user
        echo "Setting up Mule standalone server..."
        setup_server $env $host $user
    elif [ $((env)) -eq 1 ]; then
        setup_server $env
    else
        echo "Invalid environment selection"
    fi

以下是执行的输出

+ echo -e 'Which environment are you setting up?'
Which environment are you setting up?
+ echo -e '[1] local \n[2] remote'
[1] local 
[2] remote
+ echo -n 'Select your environment: '
Select your environment: + read env
1
+ '[' 1 -eq 2 ']'
+ '[' 1 -eq 1 ']'
+ setup_server 1
+ echo 'Path to the server archive:'
Path to the server archive:
+ read archive_path
/data/Downloads/Software/mule-standalone-3.4.0.tar.gz
+ '[' 1 -eq 2 ']'
+ echo 'Path to extract:'
Path to extract:
+ read extraction_path
/test
+ echo 'Directory to extract:'
Directory to extract:
+ read extraction_dir
server
+ dir_check /test server
+ echo 'Checking for the directory'
Checking for the directory
+ '[' '!' -d server ']'
+ echo 'Checking permission for creating directory'
Checking permission for creating directory
+ '[' '!' -w /test ']'
+ echo 'Changing the permission to writable'
Changing the permission to writable
+ exec sudo chmod 775 /test -R

1 个答案:

答案 0 :(得分:2)

你几乎肯定会误导exec。它用一个新进程替换当前进程,该进程执行第一个chmod出口。从脚本中删除所有'exec'调用,然后在没有它的情况下运行命令。

    exec sudo chmod 775 $1 -R

    sudo chmod 775 $1 -R

等等。