Ubuntu环境下Google Cloud中复制文件并同步进入目录的命令咨询
Hey there! Typing those repeated long paths every time you upload a file is such a tedious chore—let’s break down a few straightforward solutions to streamline this workflow, so you can spend less time typing and more time unzipping.
1. Combine Commands in One Line (Quick Fix)
The simplest immediate fix is to chain your two commands with &&, which only runs the second command if the first succeeds (so you won’t accidentally cd into the directory if the copy fails):
cp filename.zip ../../directory/ && cd ../../directory/
This works great for one-off use, but if you’re doing this multiple times, we can make it even easier.
2. Create a Shell Alias (Reusable Shortcut)
For repeated use, set up an alias that wraps both commands. Here’s how:
- Open your shell configuration file (usually
~/.bashrcfor Bash, or~/.zshrcif you use Zsh) in a text editor:nano ~/.bashrc - Add this line at the bottom (it accepts the filename as an argument):
alias cpandgo='cp "$1" ../../directory/ && cd ../../directory/' - Save and exit, then reload the configuration to apply changes:
source ~/.bashrc
Now you can run the whole workflow with just:
cpandgo filename.zip
This is perfect if your target directory (../../directory/) rarely changes.
3. Write a Custom Shell Function (Flexible & Robust)
If you want more control (like error checking for missing files), a shell function is the way to go. Add this to your ~/.bashrc or ~/.zshrc:
cp_to_target() { # Define your target directory once here local target_dir="../../directory/" # Check if the input file exists if [ -f "$1" ]; then cp "$1" "$target_dir" && cd "$target_dir" echo "Success! Copied $1 to $target_dir and moved into the directory." else echo "Error: File '$1' doesn't exist. Please check the filename." fi }
Reload your shell config with source ~/.bashrc, then use it like:
cp_to_target filename.zip
This function will warn you if you try to copy a non-existent file, which prevents frustrating mistakes.
4. Use an Environment Variable (Easy Path Updates)
If you might need to change the target directory later, define it as an environment variable first:
# Add this to ~/.bashrc to make it permanent export TARGET_DIR="../../directory/"
Then your command becomes:
cp filename.zip $TARGET_DIR && cd $TARGET_DIR
Later, if the path changes, you just update the TARGET_DIR variable instead of editing every command or alias.
内容的提问来源于stack exchange,提问作者Pasindu




