Mac系统下如何在sh文件中执行多条命令?附FTP脚本问题
Fixing FTP Batch Script Issues on macOS
Hey there! Let's break down why your script is stopping after the second command and how to fix it properly.
The Core Problem
Your initial script has two key issues:
- Incorrect shebang line: The
#!/bin/bashline should only specify the shell interpreter—you can't tack onftp open...right after it. That line tells the system which program to use to run the script, so it needs to be standalone. - Misusing shell operators with FTP: The
&&operator works for shell commands, butftpis an interactive program that runs its own command environment. When you runftp open domain.com, the shell launches the FTP client and waits for it to exit—your subsequentuser passcommands never reach the FTP client because the shell isn't processing them anymore.
The Correct Approach: FTP Batch Mode
To run multiple FTP commands automatically, you need to pass the commands directly to the FTP client using a here-document (or a batch file). Here's a working version of your script:
#!/bin/bash # Launch FTP in batch mode: # -n: Disable automatic login (so we can use the `user` command explicitly) # -i: Turn off interactive prompts (avoids asking "confirm upload?" for mput) ftp -in << FTP_COMMANDS # Connect to your remote server open domain.com # Authenticate with username and password user pass # Switch to the remote target directory cd /public_html/test_folder # Switch to your local directory with files to upload lcd /Users/mac/downloads # Set transfer mode (your "a" parameter refers to ASCII mode; use `binary` for binary files) ascii # Upload the local file named "file" mput file # Exit the FTP client quit FTP_COMMANDS
Key Details Explained
ftp -in: The-nflag prevents FTP from trying to auto-login with your macOS username, which lets you use theusercommand to specify your FTP credentials.-idisables interactive prompts, so your script runs without needing manual input.- Here-document (
<< FTP_COMMANDS): This tells the shell to send all the text between<< FTP_COMMANDSandFTP_COMMANDSdirectly to the FTP client as input. This way, FTP executes each command in sequence just like you'd type them manually. - Transfer mode: Your original "a" parameter corresponds to ASCII mode (good for text files like .txt, .html). If you're uploading binary files (images, zip archives), replace
asciiwithbinary.
Security Note
Storing your FTP password in plain text in a script is risky. For a more secure setup, you can create a ~/.netrc file in your home directory with your credentials (make sure to set permissions to 600 so only you can read it):
machine domain.com login your_username password your_password
Then you can simplify the script by removing the user pass line—FTP will automatically use the credentials from .netrc.
内容的提问来源于stack exchange,提问作者Maheralmizany




