You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

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:

  1. Incorrect shebang line: The #!/bin/bash line should only specify the shell interpreter—you can't tack on ftp open... right after it. That line tells the system which program to use to run the script, so it needs to be standalone.
  2. Misusing shell operators with FTP: The && operator works for shell commands, but ftp is an interactive program that runs its own command environment. When you run ftp open domain.com, the shell launches the FTP client and waits for it to exit—your subsequent user pass commands 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 -n flag prevents FTP from trying to auto-login with your macOS username, which lets you use the user command to specify your FTP credentials. -i disables 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_COMMANDS and FTP_COMMANDS directly 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 ascii with binary.

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

火山引擎 最新活动