簡體   English   中英

如何驗證我的 bash 腳本以顯示在提示用戶時只能輸入 2 個文件名或使用 echo 語句出錯

[英]How do I validate my bash script to show that only 2 file names can be typed when user is prompted or errors out with echo statement

#!/bin/bash # Ask for user to enter two filenames echo Please Provide 2 filenames to compare read file1 file2 # Check to see if 2 different filenames are not provided
echo "Please Provide 2 filenames to compare"

read file1 file2
if [ "$file1" == "$file2" ]
then
  echo "ERROR: file names must be different."
  exit 1
fi

echo "Good stuff!"
# Bash returns result of "echo" function here, which is 0 (success)

bash

#!/usr/bin/env bash

while read -rp 'Please enter 2 filenames to compare: ' -a file; do
  if ! (( ${#file[*]} == 2 )); then
    printf >&2 'You entered %s file, need 2 files, please try again!\n' "${#file[*]}"
  elif [[ ${file[0]} == ${file[1]} ]]; then
    printf >&2 'Both %s and %s are the same, please try again!\n' "${file[0]}" "${file[1]}"
  elif ! [[ -e ${file[0]} && -e ${file[1]} ]]; then
    printf >&2 'Either one or both of the given file does not exists, please try again!%s\n'
  else
    printf 'All ok!\n' && break
  fi
done

printf 'You entered %s and %s\n' "${file[@]}"
  • 循環繼續,直到滿足條件才退出腳本。

  • 第一個條件,如果文件小於或大於 2。

  • 第二個條件,如果兩個文件相同(相同的文件名)。

  • 第三個條件,如果兩個或一個文件不存在。

  • 如果在不滿足其中一個條件時需要退出腳本,請在elif (所有這些)塊內添加一個exit 1 ,在printf語句所在的行下方/之后。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM