给出以下Bash shell脚本摘录:
# The intent is to take the PATH env variable, break it up into its parts, making them
# appear to be command line args (i.e., `$1`, `$2`, ...), and then for this example, just
# echo the parts in space delimited form, but we can imagine that we may want to do other
# things with them - this is just sample usage
# Important Requirement/Constraint
# ================================
# Please do not alter the "PATH to $1, $2, $3, ..." portion of the answer or replace the
# Bash ".." range construct with the output of the "seq" command exec'd in a subshell.
# Preferably, the answer should simply consist of the simplification of the last line of
# code - the "eval eval ..." . Also, please don't simplify by collapsing the whole thing
# to just echo "$@" since we may want to work with only some of the parts, and not
# necessarily the first parts, of the path. That is to say that the 1 and $# in the
# {1..$#} range could be replaced with other shell variables or expr., potentially
# Test case
PATH=/usr/local/bin:/usr/bin:/bin
# The code being examined follows
# Set ':' as the input field separator of the path
IFS=: # Or, more appropriately if in a function: local IFS=:
# Parse the PATH environment variable and break it up into its components
set $PATH
# This is the line we want to simplify, if possible, without losing functionality of
# course (see the comment that follows for details)
eval eval echo '\'$(eval 'echo "\${1..$#}"')
# Some notes and explanations regarding the functionality and underlying intent of the
# preceding line:
# - We start by dynamically creating the following construct: ${1..3}
# since $# is 3 for our example
# - Use Bash to expand that construct to: $1 $2 $3
# these vars contain the parsed parts of the PATH
# - Finally, display the three parts of the PATH using echo: echo $1 $2 $3
# - This causes the following text to be sent to STDOUT:
# /usr/local/bin /usr/bin /bin
因此,可以简化前面代码中的eval eval...
行,但仍然产生所需的输出,对于上面的示例是:
/usr/local/bin /usr/bin /bin
我正在考虑一种解决方案,该解决方案将用输入/输出重定向(也许)替换某些echo
命令,或者可能需要重新排序/折叠,从而减少对{{ 1}}命令,而不是示例中使用的命令。
答案 0 :(得分:1)
echo "${PATH}" | tr ':' '\n' > stack
count=1
echo "#/bin/sh-" | tr '-' '\n' >> stack2
while read line
do
echo "path${count}=${line}" >> stack2
count=$(($count+1))
done < stack
source stack2
现在,您已经在路径的每个部分中都有自己的命名变量。
答案 1 :(得分:1)
贴近原版,即可做到
IFS=:
set $PATH
echo "$@"
如果您不想更改IFS
和PATH
,则可以
set $(sed 's/[^=]*=//;s/:/ /g' <<< ${PATH})
echo "$@"
答案 2 :(得分:0)
但仍会产生所需的输出,
/ usr / local / bin / usr / bin / bin
只是:
echo "${PATH//:/ }"
目的是获取PATH env变量,将其分解成各个部分,使它们成为 似乎是命令行参数(即
$1
,$2
,...),对于本示例, 以空间定界的形式呼应零件,但是我们可以想象我们可能想要做其他事情 事情-这只是示例用法
我不相信无引号的shell扩展。
IFS=':' read -ra patharr <<<"$PATH"
set -- "${patharr[@]}"
IFS=' '; printf "%s\n" "${patharr[*]}"