简体   繁体   English

Bash 打印除 first 之外的所有参数 - 打印返回文件名

[英]Bash print all arguments except first - print returns file names

I have a bash script which is supposed to print the arguments in two lines.我有一个 bash 脚本,它应该在两行中打印参数。 The first line should be the first argument and the second line should be the rest of the arguments第一行应该是第一个参数,第二行应该是其余的参数

#!/bin/bash

FIRST_ARG="$1"
shift
REST_ARGS="$@"

echo $FIRST_ARG
echo $REST_ARGS

This works fine for normal arguments such as这适用于普通参数,例如

root@us:~# /bin/bash parse.sh testName test1 test2 test3
testName
test1 test2 test3
root@us:~# 

However, what I want is to send a key value pair as the arguments such as但是,我想要的是发送一个键值对作为参数,例如

testName "X-Api-Key: 1be0ad48" "Name: someTest" "Interval: * * * * *"

I am expecting this to produce a result as follows我希望这会产生如下结果

testName
"X-Api-Key: 1be0ad48" "Name: someTest" "Interval: * * * * *"

Including the quotes.包括引号。 However, I am getting the following as result但是,我得到以下结果

root@us:~# /bin/bash parse.sh testName "X-Api-Key: 1be0ad48" "Name: someTest" "Interval: * * * * *"
testName
X-Api-Key: 1be0ad48 Name: someTest Interval: parse.sh parse.sh parse.sh parse.sh parse.sh
root@us:~# 

Two things happening extra here that I don't want.这里发生了两件我不想要的额外事情。 1) It removes the quotes ", 2) It replaces * with the file name. 1) 删除引号 ", 2) 将 * 替换为文件名。

I tried escaping those with " but it didn't work. Is there a way to solve this? Where am I doing wrong in this?我试着用 " 来逃避那些,但没有用。有没有办法解决这个问题?我哪里做错了?

The only sure way to stash command line arguments is in an array:存储命令行参数的唯一可靠方法是在数组中:

#!/bin/bash

first_arg="$1"
shift
rest_args=("$@")
# ........^....^

# show how bash has stored these variables
declare -p first_arg
declare -p rest_args

echo "first = $first_arg"
for arg in "${rest_args[@]}"; do
    echo "arg = $arg"
done

Get out of the habit of using ALLCAPS variable names, leave those as reserved by the shell.改掉使用 ALLCAPS 变量名的习惯,将它们保留为 shell 保留。 One day you'll write PATH=something and then wonder why your script is broken .有一天你会写PATH=something然后想知道为什么你的脚本被破坏了

the * are expanded because you are doing a echo without quoting $REST_ARGS . *被扩展,因为您正在执行echo而不引用$REST_ARGS try adding quotes like this:尝试添加这样的引号:

#!/bin/bash

FIRST_ARG="$1"
shift
REST_ARGS="$@"

echo "$FIRST_ARG"
echo "$REST_ARGS"

a solution to keep the double quotes would be to quote the strings using single quote ' like this:保留双引号的解决方案是使用单引号'引用字符串,如下所示:

$ bash parse.sh testName '"X-Api-Key: 1be0ad48"' '"Name: someTest"' '"Interval: * * * * *"'
testName
"X-Api-Key: 1be0ad48" "Name: someTest" "Interval: * * * * *"
$

Does what you ask for:是否满足您的要求:

#!/usr/bin/env sh

echo "$1"
shift
printf '"%s" ' "$@"
# or alternatively:
# env printf '%q ' "$@"
echo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM