将命令行参数传递给期望命令

问题描述 投票:0回答:1

我正在尝试编写一个bash脚本,它将用户名作为命令行参数。它应该使用提供的用户名登录系统并执行命令。

expect -c 'spawn su - other_user_name -c my_bash_command; expect "Password :"; send my_password\n; interact'

如果我提供所需的变量,则应为:

expect -c 'spawn su - $1 -c ps ax | grep java | cut -f2 -d " " - | xargs kill -9; expect "Password :"; send Temp/123\n; interact'

其中$1是传递的用户名,ps ax | grep java | cut -f2 -d " " - | xargs kill -9是该用户执行的命令。如果我传递参数,它说没有这样的变量。如果我在脚本顶部写了#!/usr/bin/expect,则它不起作用。我需要修复它。

linux bash shell expect
1个回答
0
投票

解决peynexj的有效问题,并通过环境传递期望的用户名(并添加换行符以提高可读性):

env user="other_user_name" expect -c '
    spawn sh -c "su - $env(user) -c ps ax | grep java | cut -f2 -d \" \" - | xargs kill -9"
    expect "Password :"
    send Temp/123\n
    interact
'
© www.soinside.com 2019 - 2024. All rights reserved.