Как я могу постоянно исправить опечатки в моей последней команде Bash?

Как только они получат жесткий диск, им вряд ли понадобится ваш пароль. Они просто монтируют все разделы в соответствии с /etc/fstab. Следующий шаг - sudo su - "id вашей учетной записи" (если ваш id - 501, просто sudo su - 501).

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

Это "немногое" включает в себя:

  • Не используйте обычный текстовый пароль в скриптах (например, в задании cron, собирающем электронную почту (...=pop("me@google.com", "avreyclverpassword"), доступ к удаленным хостам и т.д.)
  • Не используйте ключи без пароля gpg и ssh. (Набирайте их каждый раз заново или используйте агент для хранения их в памяти.)
1
17.07.2018, 06:17
2 ответа

HSTR казался привлекательным, но на мой вкус оказался слишком тяжелым.

Вместо этого я написал собственную функцию bash:

# Removes the last command from the history that matches the given search
# string and re-executes it using the given replacement string.
#
# Usage:
#   historysub SEARCH [REPLACEMENT]
#   historysub -d SEARCH
#
#   REPLACEMENT may be omitted to remove SEARCH from the executed command.
#
#   -d removes the last command matching SEARCH from the history without
#   executing a new command.
historysub()
{
  local delete=0
  local usage=0
  local OPTIND=1
  while getopts ":hd" option; do
    case "${option}" in
      d) delete=1 ;;
      h) usage=1 ;;
      ?) usage=2 ;;
    esac
  done
  shift $((OPTIND - 1))

  local search="${1-}"
  local replacement="${2-}"

  usage_text=
  usage_text+="Usage: ${FUNCNAME[0]} SEARCH [REPLACEMENT]\n"
  usage_text+="       ${FUNCNAME[0]} -d SEARCH\n"

  if (( usage )); then
    echo -e "${usage_text}"
    return $(( usage - 1 ))
  fi

  if [[ -z "${search}" ]]; then
    echo -e "${usage_text}" >&2
    return 1
  fi

  # RE to parse the `history` output.
  local hist_re='^[ \t]*([0-9]+)[ \t]+(.+)$'

  local hist_full
  hist_full=$(HISTTIMEFORMAT="" history)

  # We don't want the search string to accidentally match against history
  # numbers, so split the `history` output so that we can search against just
  # the commands.
  local hist_nums hist_cmds
  hist_nums=$(sed -E "s/${hist_re}/\1/" <<< "${hist_full}")
  hist_cmds=$(sed -E "s/${hist_re}/\2/" <<< "${hist_full}")

  # Find the last matching history entry (excluding ourself).
  local matches last_match
  matches=$(grep -nF -- "${search}" <<< "${hist_cmds}")
  last_match=$(grep -vF -- "${FUNCNAME[0]}" <<< "${matches}" | tail -n 1)

  if [[ -z "${last_match}" ]]; then
    echo "${FUNCNAME[0]}: \"${search}\" not found." >&2
    return 1
  fi

  # RE to parse the `grep -n` output.
  local line_re='^([0-9]+):[ \t]*(.+)$'

  # Note that the line number and the history number might not be the same, so
  # we need to retrieve the original history number.
  local line_num hist_cmd hist_num
  line_num=$(sed -E "s/${line_re}/\1/" <<< "${last_match}")
  hist_cmd=$(sed -E "s/${line_re}/\2/" <<< "${last_match}")
  hist_num=$(tail -n +${line_num} <<< "${hist_nums}" | head -n 1)

  history -d "${hist_num}"
  if (( delete )); then
    echo "Removed: ${hist_cmd}"
    return 0
  fi

  local cmd="${hist_cmd/${search}/${replacement}}"
  echo "${cmd}"

  # Add the new command to the history.
  history -s -- "${cmd}"
  eval -- "${cmd}"
}

Итак, теперь я могу запустить historysub TYPO CORRECTIONдля повторного -выполнения команды с исправлением. Это не так хорошо, как возможность интерактивно редактировать старую команду, но я думаю, что этого должно быть достаточно для моих нужд.

0
27.01.2020, 23:18

Опция #1 -Вручную

Я просто открывал файл ~/.bash_historyв редакторе, таком как vim, вносил в него необходимые изменения и сохранял.

$ vim ~/.bash_history

Перед редактированием убедитесь, что ваша текущая история терминалов также привязана к этому файлу.:

$ history -a

Имейте в виду, что ваш файл истории расположен там, где эта переменная среды указывает на:

$ echo $HISTFILE
/Users/user1/.bash_history

Опция #2 -HSTR

Существует инструмент командной строки под названием HSTR, который можно использовать для более систематического управления файлом ~/.bash_history. На основном веб-сайте HSTR были видеоролики и подробная информация о его использовании.

Здесь также упоминается эта реклама:

HSTR can also manage your command history (for instance you can remove commands that are obsolete or contain a sensitive information) or bookmark your favorite commands.

Подробнее об этом см. в полной документации:ДОКУМЕНТАЦИЯ HSTR .

Ссылки

4
27.01.2020, 23:18

Теги

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