Выполнение переменных Bash: методы и примеры кода

Команда

или синтаксис $(). Вот несколько примеров:

  1. Использование команды eval:

    command="ls -l"
    eval "$command"  # Executes the value of the 'command' variable as a command
  2. Использование синтаксиса $():

    command="ls -l"
    $command  # Executes the value of the 'command' variable as a command
  3. Использование команды sourceдля выполнения сценария, хранящегося в переменной:

    script="#!/bin/bash\n echo 'Hello, World!'"
    source <(echo "$script")  # Executes the script stored in the 'script' variable
  4. Использование параметра bash -cдля выполнения команды, хранящейся в переменной:

    command="echo 'Hello, World!'"
    bash -c "$command"  # Executes the command stored in the 'command' variable