Find 命令在终端中有效,但在自动 shell 脚本中无效

Find 命令在终端中有效,但在自动 shell 脚本中无效

我正在编写一个脚本,每当插入 USB 时,它都会自动将 sqlite 文件从我的计算机复制到 USB 上。它会在 USB 上创建一个新目录,该目录采用计算机的主机名,因为我将从多台计算机下载。

脚本如下:

#!/bin/bash
# Set the source folder to download from
src_dir="/home/atlas/atlas/runs/server"

# Define hostname 
usb_hostname=$(cat /etc/hostname)

# Find USB path
usb_path=$(find /media/atlas/*/ -maxdepth 0 -type d -print -quit)
echo "USB path = $usb_path"

# Set the destination 
dest_dir=$usb_path$usb_hostname

# Mount the USB device
sudo mount -t vfat /dev/sd?1 dest_dir

# Create a directory on the USB stick 
sudo mkdir -p $dest_dir

# Copy the files with 'sqlite' in the extension from the source folder to the destination folder
find $src_dir -type f -iname "*sqlite*" -exec cp {} $dest_dir \;

# Unmount the USB device
sudo umount dest_dir

当我在终端中运行该脚本时,它运行完美,但是当它在插入时运行时,它会在“find”命令(行“usb_path =”)上失败,并返回“没有这样的文件或目录”。

我尝试过的事情:

  • 在脚本开始时设置“sleep 5”以留出时间进行挂载;我也延长了这个时间,但没有任何变化
  • 检查脚本访问 /media/atlas/ 目录的权限
  • 系统日志文件中没有错误
  • 'atlas' 是我的用户;如果我将其更改为 $(whoami),脚本会将路径更改为 /media/root/,并且找不到任何目录
  • USB 设备已正确安装(正如我所说,脚本在终端上运行良好)
  • 我已经检查过,脚本确实识别 /media/atlas,只是无法识别任何子目录

我现在已经束手无策了。我知道问题在于,当自动运行时,shell 脚本无法在 /media/atlas/ 内找到任何目录,但我不知道原因。任何建议都将不胜感激。

相关内容