「dd」コマンドを安全にすることはできますか?

「dd」コマンドを安全にすることはできますか?

私たち全員(または誰かを知っている)は誤ってdestroy-diskdd)注文する。次のような方法でコマンドを変更する方法(ある場合)は何ですか?/dev/sda出力ファイル(of=/dev/sda)として提供されると、コマンドは実行されないか、「続行しますか?」などの確認メッセージは表示されません。

.bashrc ファイルで似たようなものを取得できますか?

通常、特定のパラメータを渡すときに特定のコマンドの実行を停止する方法はありますか?

編集する:このコマンドはrootとして実行されます。

ベストアンサー1

Arkadiuszが言ったように、ラッパーを作ることができます。

dd() {
  # Limit variables' scope
  local args command output reply

  # Basic arguments handling
  while (( ${#} > 0 )); do
    case "${1}" in
    ( of=* )
      output="${1#*=}"
      ;;
    ( * )
      args+=( "${1}" )
      ;;
    esac
    shift || break
  done

  # Build the actual command
  command=( command -- dd "${args[@]}" "of=${output}" )

  # Warn the user
  printf 'Please double-check this to avoid potentially dangerous behavior.\n' >&2
  printf 'Output file: %s\n' "${output}" >&2

  # Ask for confirmation
  IFS= read -p 'Do you want to continue? (y/n): ' -r reply

  # Check user's reply
  case "${reply}" in
  ( y | yes )
    printf 'Running command...\n' >&2
    ;;
  ( * )
    printf 'Aborting\n' >&2
    return
    ;;
  esac

  # Run command
  "${command[@]}"
}

例:

$ dd if=/dev/urandom of=file.txt bs=4M count=5
Please double-check this to avoid potentially dangerous behavior.
Output file: file.txt
Do you want to continue? (y/n): y
Running command...
5+0 records in
5+0 records out
20971520 bytes (21 MB, 20 MiB) copied, 0.443037 s, 47.3 MB/s

必要に応じて修正してください(POSIX互換、他の条件の確認など)。

おすすめ記事