如何从Shell提示符持续循环命令并根据输入名称批量创建目录
Hey there! Let's tackle your two shell scripting questions step by step—they're common pain points, so I've got you covered.
There are a couple of straightforward ways to keep running a command repeatedly:
Using a
while trueloop: This gives you full control over the loop, like adding delays or custom exit conditions. For example, to rundateevery 2 seconds:while true; do date sleep 2 # Adjust the delay as needed donePress
Ctrl+Canytime to stop the loop. You can replacedatewith any command you want to repeat.Using the
watchcommand: If you just need to run a command at regular intervals without extra logic,watchis perfect. It even clears the screen each time by default. For example, to check disk usage every 3 seconds:watch -n 3 df -hThe
-nflag sets the interval in seconds (default is 2). Again,Ctrl+Cstops it.
Instead of hardcoding fixed read variables and repeated mkdir commands, we can use arrays and loops to handle as many names as the user wants. Here are a few flexible approaches:
Option 1: Single input with space-separated names
Let the user type all names at once, separated by spaces, then create directories for each:
read -p "Enter user/s (space-separated): " -a user_list for username in "${user_list[@]}"; do mkdir -p "$username" # -p avoids errors if the directory already exists echo "Created directory: $username" done
- The
-a user_listflag stores all input names into an array calleduser_list. - The
forloop iterates over every element in the array, creating a directory for each name.
Option 2: Multiple lines of input (until user finishes)
If you want users to enter one name per line, and stop when they press Ctrl+D (EOF):
echo "Enter user names (one per line; press Ctrl+D when done):" while read -r username; do mkdir -p "$username" echo "Created directory: $username" done
- The
-rflag inreadprevents backslashes from being treated as escape characters (safer for names with special chars).
Option 3: Continuous prompt until user chooses to exit
If you want to keep asking for names until the user types a keyword like "quit":
while true; do read -p "Enter user/s (space-separated, or type 'quit' to exit): " -a user_list # Check if the first input is "quit" to exit the loop if [[ "${user_list[0]}" == "quit" ]]; then echo "Exiting..." break fi # Create directories for each name for username in "${user_list[@]}"; do mkdir -p "$username" echo "Created directory: $username" done done
This lets the user add batches of names multiple times without restarting the script.
All these methods eliminate the need for repetitive read and mkdir lines—they scale to as many names as the user wants to input!
内容的提问来源于stack exchange,提问作者MOth Balls10

