Передача переменной из одной функции в другую в сценарии bash

Я решил эту проблему при загрузке kde neon и вручную установил grub, набрав sudo grub-installи обновив grub, набрав sudo update-grub. Когда мне нужно загрузиться с Primeos, я выбираю его в биосе. Я добавлю запись для него позже.

0
05.05.2020, 15:53
1 ответ

Способ передачи данных из одной функции в другую зависит от вашего варианта использования -.

Я не смог воспроизвести вашу ошибку -, возможно, она как-то связана с awsили s3cmd. использование обратных кавычек, поскольку подоболочка устарело -, вы должны использовать $().

Если вы просто хотите передавать данные и не заинтересованы в их хранении на жестком диске, вы можете использовать глобальные массивы (все, что вы не объявляете иначе, является глобальным):

#!/usr/bin/env bash

command_to_get_files() {
  local ifs
  # store the internal field separator in order to change it back once we used it in the for loop
  ifs=$IFS
    # change IFS in order to split only on newlines and not on spaces (this is to support filenames with spaces in them)
  IFS='
'
  # i dont know the output of this command but it should work with minor modifications
  # used for tests:
  # for i in *; do
  for file in $(aws s3 ls "s3://path1/path2/" | awk '{print $2}'); do
    # add $file as a new element to the end of the array
    files+=("${file}")
  done
  # restore IFS for the rest of the script to prevent possible issues at a later point in time
  IFS=${ifs}
}

# needs a non-empty files array
command_to_get_filesizes() {
  # check if the number of elements in the files-array is 0
  if (( 0 == ${#files[@]} )) then
    return 1
  fi
  local index
  # iterate over the indices of the files array
  for index in "${!files[@]}"; do
    # $(( )) converts the expression to an integer - so not found files are of size 0
    filesizes[${index}]=$(( $(s3cmd du -r "s3://path1/path2/${files[${index}]}" | awk '{print $1}') ))
    # used for testing:
    # filesizes[${index}]=$(( $(stat -c %s "${files[$i]}") ))
  done
}

command_to_get_files
command_to_get_filesizes

# loop over indices of array (in our case 0, 1, 2,...)
for index in "${!files[@]}"; do
  echo "${files[${index}]}: ${filesizes[${index}]}"
done

примечания о массивах bash:

  • получить размер массива:${#array[@]}
  • получить размер первого элемента:${#array[0]}
  • получить индексы массива:${!array[@]}
  • получить первый элемент массива:${array[0]}

для получения дополнительной информации о массивах см. здесь .

другой метод может состоять в том, чтобы просто echoимена и предоставить их в качестве параметров другой функции (это сложно с именами файлов, состоящими -из нескольких слов)

Использование временных файлов может привести к такому результату:

#!/usr/bin/env bash

readonly FILES=$(mktemp)
readonly FILESIZES=$(mktemp)

# at script exit remove temporary files
trap cleanup EXIT
cleanup() {
  rm -f "$FILES" "$FILESIZES"
}

command_to_get_files() {
  aws s3 ls "s3://path1/path2/" | awk '{print $2}' >> "$FILES"
}

command_to_get_filesizes() {
  while read -r file; do
    s3cmd du -r "s3://path1/path2/${file}" | awk '{print $1}' >> "$FILESIZES"
  done < "$FILES"
}

command_to_get_files
command_to_get_filesizes
2
28.04.2021, 23:16

Теги

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