隐藏或抑制传递给shell脚本的参数值



在本地机器上,我在远程服务器上运行shell脚本,并向脚本传递一些参数。像test.sh"一样;name"年龄;这是我的脚本:

#!/bin/bash
echo $1
echo $2

在远程服务器上,当脚本执行时,如果我运行ps aux | grep .sh,我可以看到这两个参数的值。像bash的名字年龄

有没有一种方法可以抑制或隐藏正在运行的shell进程中的值,以便查看参数?

我有个主意。您可以创建一个具有唯一名称的全局环境变量,并将位置参数保存在那里,然后重新执行流程并获得参数:

#!/bin/bash
if [[ -z "$MYARGS" ]]; then
export MYARGS="$(printf "%q " "$@")"
exec "$0"
fi
eval set -- "$MYARGS"
printf -- "My arguments:n"
printf -- "-- %sn" "$@"
sleep infinity

它将对ps aux:隐藏它

$ ps aux | grep 1.sh
kamil     196704  0.4  0.0   9768  2084 pts/1    S+   16:49   0:00 /bin/bash /tmp/1.sh
kamil     196777  0.0  0.0   8924  1640 pts/2    S+   16:49   0:00 grep 1.sh

环境变量仍然可以从/proc:中提取

$ cat /proc/196704/environ | sed -z '/MYARGS/!d'; echo
MYARGS=1 2 3 54 5 

另一种方法可能是将位置参数作为字符串写入stdin,并将其传递给具有原始输入的outself:

#!/bin/bash
if [[ -z "$MYARGS" ]]; then
export MYARGS=1 # just so it's set
# restart outselves with no arguments
exec "$0" < <(
# Stream arguments on stdin on one line
printf "%q " "$@" | xxd -p | tr -d 'n'
echo
exec cat
)
fi
IFS= read -r args # read _one line_ of input - it's our arguments
args=$(xxd -r -p <<<"$args") # encoded with xxd
eval set -- "$args"
printf -- "My arguments:n"
printf -- "-- %sn" "$@"
sleep infinity

以下是从stdin:中获取命令行args读取args的方法

#!/usr/bin/env bash
args=()
for arg; do
printf "%dt%sn" $((++c)) "$arg"
args+=("$arg")
done
if ! [[ -t 0 ]]; then
while IFS= read -r arg; do
args+=("$arg")
done
fi
declare -p args

你能做什么:

script.sh hello world
printf "%sn" hello world | script.sh
echo world | script.sh hello

最新更新