Bash脚本出现`syntax error near unexpected token 'fi'`错误求助
syntax error near unexpected token 'fi' in Your Bash Script Hey there! Let's break down the syntax issues in your script step by step—these are what's causing the unexpected token error and other logic problems:
1. Incorrect if condition syntax
Your if statement uses [ ] (the test command) incorrectly when trying to run a pipeline. The [ ] is meant for evaluating conditional expressions, not for running commands and checking their exit status. To check if grep finds a match, you can directly use the pipeline in the if condition without [ ]:
if who -u | grep -q "^$user"; then
The -q flag makes grep run quietly (no output), and its exit code will be 0 (success) if a match is found—this is exactly what the if statement checks for to trigger the then block.
2. Wrong command substitution for variable assignment
Your fullname assignment doesn't capture the output of the getent command. To store command output in a variable, wrap the entire command in $(...) (the modern, preferred command substitution syntax):
fullname=$(getent passwd "$user" | cut -d: -f5)
Also, always wrap variables like "$user" in double quotes to handle edge cases (like usernames with spaces, though rare, it's a good defensive practice).
3. Missing quotes around variables
When referencing $user in the echo statements, wrap it in double quotes to avoid issues with special characters or empty values.
Corrected Full Script
#!/bin/bash user="$1" if who -u | grep -q "^$user"; then fullname=$(getent passwd "$user" | cut -d: -f5) echo "User $fullname is logged in" else echo "User $user is not logged in" fi
Extra Bonus Tip
If you want to make sure the script receives a username argument (so it doesn't fail silently if run without one), add this check at the very start:
if [ $# -eq 0 ]; then echo "Please provide a username as an argument." exit 1 fi
内容的提问来源于stack exchange,提问作者andra

