Назначьте результат переданной команды, если она завершится успешно

PUBKEY=$(cat ~/.ssh/id_rsa.pub); grep -q "$PUBKEY"  ~/.ssh/authorized_keys || echo "$PUBKEY" >> ~/.ssh/authorized_keys

Этот один лайнер проверяет, присутствует ли уже пабки в файле authorized_keys, и добавляет его в конец файла, если его нет.

~/.ssh/id_rsa.pub вот путь к добавляемому пабки

~/. ssh/authorized_keys здесь путь к целевому файлу authorized_keys (~ символ обозначает ``

Для удалённого хоста можно использовать ssh-copy-id

1
28.02.2018, 11:36
3 ответа

El shell tiene varias formas nativas de analizar la primera palabra de una cadena:

  1. Recortar por sufijo-${a%% *}

  2. Asigne a los parámetros posicionales-set -- ${a}-el resultado estará en $1. Puede simplificar esto con set -- $(func 1).

  3. Divida en elementos de matriz(bashsolo)-a=( $(func 1) )-el resultado estará en ${a[0]}.

0
27.01.2020, 23:32

Podría usar set -o pipefailpara obtener el error de la parte anterior de la canalización:

The return status of a pipeline is the exit status of the last command, unless the pipefail option is enabled. If pipefail is enabled, the pipeline's return status is the value of the last (rightmost) command to exit with a non-zero status, or zero if all commands exit successfully.

$ foo() { [[ "$1" = 1 ]] || return 1; echo "hello world"; }
$ a=$(set -o pipefail; foo 2 | awk '{print $1}' || echo "fail..." >&2)
fail...

Pero realmente, no veo por qué asignar dos veces sería un problema. En esencia, solo modifica el valor que obtuvo si el comando tiene éxito, o lo ignora si falla.

Además, puedes condensar un poco esa lógica:

if a=$(foo 1); then
   a=${a%% *};
   echo "first word of a is '$a'"; 
   # do some work with $a...
else
   echo "error..." >&2;
fi

impresiones

first word of a is 'hello'
2
27.01.2020, 23:32

Un problema con su código es que golpea aincluso si la función funcdevuelve un resultado que no -es cero.

En cambio:

#!/bin/sh

func () {
    if [ "$1" -eq 1 ]; then
        echo 'some sort of logging stuff' >>logfile
        return 1
    fi

    echo 'hello world'
}

a="a string"

if b=$( func 0 ); then
    a=${b%% *}
fi

printf '1: a = "%s"\n' "$a"

a="a string"

if b=$( func 1 ); then
    a=${b%% *}
fi

printf '2: a = "%s"\n' "$a"

Ejecutar esto producirá

1: a = "hello"
2: a = "a string"

Como puede ver, en el segundo caso, aconserva su valor.

0
27.01.2020, 23:32

Теги

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