> For the complete documentation index, see [llms.txt](https://docs.couchdrop.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.couchdrop.io/walkthroughs/sftp-recipes/using-sftp-clients/using-sftp-with-bash.md).

# Using SFTP with Bash

You can use the `sftp` command-line utility directly in a Bash script to perform SFTP operations. Here's a basic guide on how to use SFTP with Bash:

1. **Connecting to an SFTP Server**: You can use the `sftp` command to establish a connection to an SFTP server. Below is an example of how to connect to an SFTP server:

   ```bash
   #!/bin/bash

   HOST="sftp.example.com"
   USERNAME="your_username"
   PASSWORD="your_password"
   PORT=22

   sftppass -p "$PASSWORD" sftp -oPort=$PORT $USERNAME@$HOST
   ```

   Replace `"sftp.example.com"` with the hostname or IP address of your SFTP server, `"your_username"` with your username, and `"your_password"` with your password. You can also adjust the port number if your SFTP server uses a different port.
2. **Performing SFTP Operations**: Once connected, you can execute SFTP commands interactively or within the script to perform various operations such as uploading files, downloading files, listing directory contents, creating directories, etc. For example:
   * **Uploading a file**:

     ```bash
     put /path/to/local/file.txt /path/to/remote/file.txt
     ```
   * **Downloading a file**:

     ```bash
     get /path/to/remote/file.txt /path/to/local/file.txt
     ```
   * **Listing directory contents**:

     ```bash
     ls /path/to/remote/directory
     ```
   * **Creating a directory**:

     ```bash
     mkdir /path/to/remote/new_directory
     ```
3. **Exiting SFTP**: Once you've finished with your SFTP operations, you can exit the SFTP session by typing `exit` or by sending an EOF (End-of-File) signal (usually by pressing `Ctrl+D`).
4. **Using Password in Bash Script**: Storing passwords directly in Bash scripts is not recommended for security reasons. However, if you need to automate SFTP operations in a script, you can use tools like `sshpass` to provide the password securely. Make sure to install `sshpass` first (e.g., `sudo apt-get install sshpass` on Debian-based systems).

   Here's an example of how to use `sshpass` in a Bash script:

   ```bash
   #!/bin/bash

   HOST="sftp.example.com"
   USERNAME="your_username"
   PASSWORD="your_password"
   PORT=22

   sshpass -p "$PASSWORD" sftp -oPort=$PORT $USERNAME@$HOST <<EOF
   # SFTP commands go here
   EOF
   ```

   Replace `"your_password"` with your actual password. This approach securely provides the password to the `sftp` command without exposing it in the script itself.

By following these steps, you can use Bash scripts to automate SFTP operations securely. Ensure that you handle errors and exceptions appropriately in your scripts.
