Правильное экранирование / сохранение кавычек в функции bash [дубликат]

Если вы используете bash (или zsh или ksh93), вы можете просто сделать:

echo "$((10**($RANDOM%3+1)))"

или

var=$((10**($RANDOM%3+1)))

назначить его на var

2
16.11.2018, 02:14
2 ответа

Если указать каждый параметр в кавычках, он будет правильно обработан как позиционный параметр:

#!/usr/local/bin/bash
f() {
  echo "function was called with $# parameters:"
  while ! [[ -z $1 ]]; do
    echo "  '$1'"
    shift
  done
}
f "param 1" "param 2" "a third parameter"
$./459461.sh
function was called with 3 parameters:
  'param 1'
  'param 2'
  'a third parameter'

Обратите внимание, однако, что содержащий (i. е. самые внешние )кавычки являются , а не частью самого параметра. Давайте попробуем немного другой вызов функции:

$ tail -n1 459461.sh
f "them's fightin' words" '"Holy moly," I shouted.'
$./459461.sh
function was called with 2 parameters:
  'them's fightin' words'
  '"Holy moly," I shouted.'

Обратите внимание, что символы 'в выходных данных, окружающие воспроизводимые параметры, исходят из оператора echoв функции, а не из самих параметров.

Чтобы придать вашему коду примера больше кавычек -, мы можем сделать это:

C=mycommand
f() {
  $C "unchanging first parameter" "$1"
}
# let's call it
f 'another string that includes many spaces and double quotes'

Или это:

C=mycommand
f() {
  $C "$1" "$2"
}
# let's call it
f 'Some string with "quotes" that are scary' 'some other "long" string'
0
27.01.2020, 22:31

Пробелы не допускаются (и не допускаются )в присваивании переменной, если она не заключена в кавычки.

В

C=mycommand 'string that includes many spaces and double quotes'

Пробел без кавычек, который разбивает строку на два отдельных слова.

Одним из возможных решений является:

CMD=mycommand
s1='string that includes many "spaces" and "double" quotes'
function f {
    "$CMD" "$s1" "$1"
}
# let's call it
f 'another string that includes many "spaces" and "double" quotes'

Однако «лучшей практикой» является использование массива:

#!/bin/bash
# Define the functions to use:
mycommand(){ echo "Number of arguments: $#"
             echo "Full command called:"
             echo "mycommand" "$@"
           }
f (){
        "${cmd[@]}" "$1"
    }

# Define the command to be executed:
cmd=( mycommand 'string that includes many "spaces" and "double" quotes' )

# let's call it:
f 'another string that includes many "spaces" and "double" quotes'

При выполнении будет напечатано:

$./script
Number of arguments: 2
Full command called:
mycommand string that includes many "spaces" and "double" quotes another string that includes many "spaces" and "double" quotes
0
27.01.2020, 22:31

Теги

Похожие вопросы