Macos 如何在bash脚本中使用错误代码

Macos 如何在bash脚本中使用错误代码,macos,bash,shell,expect,Macos,Bash,Shell,Expect,抱歉如果之前有人问过我,我无法找到答案 我已经为OSX创建了一个bash脚本来装载AFP共享。该脚本工作成功,允许用户使用cocoa对话框在图形弹出窗口中键入用户名和密码 我的问题是,如果用户名和密码输入不正确,我希望能够显示一个新的弹出窗口来解释这一点 我试图根据脚本的退出状态执行此操作,但无论装载是否成功,脚本都返回0 剧本如下: cd=/etc/cocoaDialog.app/Contents/MacOS/cocoaDialog rvUsername=($($cd standard-in

抱歉如果之前有人问过我,我无法找到答案

我已经为OSX创建了一个bash脚本来装载AFP共享。该脚本工作成功,允许用户使用cocoa对话框在图形弹出窗口中键入用户名和密码

我的问题是,如果用户名和密码输入不正确,我希望能够显示一个新的弹出窗口来解释这一点

我试图根据脚本的退出状态执行此操作,但无论装载是否成功,脚本都返回0

剧本如下:

cd=/etc/cocoaDialog.app/Contents/MacOS/cocoaDialog

rvUsername=($($cd standard-inputbox --title "Network Mount" --informative-text "Please enter your username"))

username=${rvUsername[1]}

rvPassword=($($cd secure-standard-inputbox --title "Network Mount" --informative-text "Please enter your password"))

password=${rvPassword[1]}

mkdir "/Volumes/Test"

expect <<- DONE
  set timeout -1
  spawn /sbin/mount_afp -i "afp://servername/Software" /Volumes/Test

  expect "*?ser:*"
  send "$username\n"

  expect "*?assword:*"
  send "$password\r"

  expect EOF
DONE
所以mount_afp给了我一条消息,我想在我的脚本中使用它…但是退出代码是0,我不知道如何获得该消息来使用


有什么想法吗?(希望这是有意义的!)

要获取生成的命令的退出代码,请使用以下内容:

# wait for the command to end : wait for the prompt $ followed by space
expect "\\$ "
send "echo \$?\r"
expect -re "(\\d+)" {
    set result $expect_out(1,string)
}
send_user "command exit with result code : $result"

这将获取变量
$?
(前一个结束的命令的退出代码)的内容,并将其保存到
$result

要获取生成的命令的退出代码,请使用以下方法:

# wait for the command to end : wait for the prompt $ followed by space
expect "\\$ "
send "echo \$?\r"
expect -re "(\\d+)" {
    set result $expect_out(1,string)
}
send_user "command exit with result code : $result"

这将获取变量
$?
(这是前一个结束命令的退出代码)的内容,并将其保存到
$result

谢谢您的回答,所有这些都为我指明了正确的方向

我最终采用了这种方法,并将expect命令设置为变量

output=$(su -l $loggedInUser -c expect <<- DONE
  set timeout -1
  spawn /sbin/mount_afp -i "afp://$serverName" /Volumes/mount

  expect "*?ser:*"
  send "$username\n"

  expect "*?assword:*"
  send "$password\r"

  expect EOF
DONE)

output=$(su-l$loggedInUser-c expect谢谢大家的回复,帮助我找到了正确的方向

我最终采用了这种方法,并将expect命令设置为变量

output=$(su -l $loggedInUser -c expect <<- DONE
  set timeout -1
  spawn /sbin/mount_afp -i "afp://$serverName" /Volumes/mount

  expect "*?ser:*"
  send "$username\n"

  expect "*?assword:*"
  send "$password\r"

  expect EOF
DONE)

output=$(su-l$loggedInUser-c expect您需要让
expect
捕获
mount\u afp
的退出代码(以及消息的stderr)并以某种方式将其返回到shell。查看
expect
的文档,而不是shell。您需要让
expect
捕获退出代码(以及消息的stderr)装载afp并以某种方式将其返回shell。请查看
expect
的文档,而不是shell。