bash脚本从.txt中提取变量,在尝试使用mount命令时不断给出语法错误

时间:2012-06-06 03:29:15

标签: bash sh

我一直试图让这个工作在上周工作,但无法弄清楚为什么这不起作用。我将混合结果直接输入到终端中,但在从.sh运行时不断收到语法错误消息。使用ubuntu 11.10

看起来mount命令的一部分被推送到下一行而不允许它正常完成..我不知道为什么会发生这种情况或者如何阻止它进入第二行。

我在mounts.txt中有以下几行定义,从下面的mount-drives.sh读取

我已将其命名为使用sudo运行,因此它不应该是权限问题。

感谢您查看,如果需要其他信息,请与我们联系。

mounts.txt

    mountname,//server/share$,username,password,

mount-drives.sh --- origional,在下面更新

    #!/bin/bash
    while read LINE;
    do 

    # split lines up using , to separate variables
    name=$(echo $LINE | cut -d ',' -f 1)
    path=$(echo $LINE | cut -d ',' -f 2)
    user=$(echo $LINE | cut -d ',' -f 3)
    pass=$(echo $LINE | cut -d ',' -f 4)

    echo $name
    echo $path
    echo $user
    echo $pass


    location="/mnt/test/$name/"

    if [ ! -d $location ]
    then
        mkdir $location
    fi

    otherstuff="-o rw,uid=1000,gid=1000,file_mode=0777,dir_mode=0777,username=$user,password=$pass"

    mount -t cifs $otherstuff $path $location

    done < "/path/to/mounts.txt";

mount-drives.sh ---已更新

    #!/bin/bash

    while read LINE
    do
        name=$(echo $LINE | cut -d ',' -f 1)
        path=$(echo $LINE | cut -d ',' -f 2)
        user=$(echo $LINE | cut -d ',' -f 3)
        pass=$(echo $LINE | cut -d ',' -f 4)
        empty=$(echo $LINE | cut -d ',' -f 5)
        location="/mount/test/$name/"
        if [ ! -d $location ]
        then
            mkdir $location
        fi
        mounting="mount -t cifs $path $location -o username=$user,password=$pass,rw,uid=1000,gid=1000,file_mode=0777,dir_mode=0777"
        $mounting
        echo $mounting >> test.txt
     done < "/var/www/MediaCenter/mounts.txt"

2 个答案:

答案 0 :(得分:0)

在黑暗中刺伤(阅读评论后)。 “$ pass”正在拾取换行符,因为mounts.txt是在windows中创建的,并且具有Windows行结尾。尝试将echo $pass行更改为:

echo ---${pass}---

并查看是否所有内容都正确显示。

答案 1 :(得分:0)

这里有很多可以改进的地方。考虑以下 - 更紧凑,更正确的方法:

while IFS=, read -u 3 -r name path user pass empty _; do
  mkdir -p "$location"
  cmd=( mount \
    -t cifs \
    -o "rw,uid=1000,gid=1000,file_mode=0777,dir_mode=0777,username=$user,password=$pass" \
    "$path" "$location" \
  )
  printf -v cmd_str '%q ' "${cmd[@]}" # generate a string corresponding with the command
  echo "$cmd_str" >>test.txt          # append that string to our output file
  "${cmd[@]}"                         # run the command in the array
done 3<mounts.txt

与原始版本不同,即使您的路径或位置值包含空格,它也能正常工作。

相关问题