首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从bash脚本调用bash脚本

从bash脚本调用bash脚本
EN

Stack Overflow用户
提问于 2022-01-14 17:12:53
回答 1查看 175关注 0票数 0

我制作了两个程序,我试图从另一个程序中调用一个程序,但是这个程序出现在我的屏幕上:

代码语言:javascript
复制
cp: cannot stat ‘PerShip/.csv’: No such file or directory
cp: target ‘tmpship.csv’ is not a directory

该怎么办呢。这是节目。有人能帮帮我吗?

代码语言:javascript
复制
#!/bin/bash
shipname=$1
imo=$(grep "$shipname" shipsNAME-IMO.txt | cut -d "," -f 2)
cp PerShip/$imo'.csv' tmpship.csv
dist=$(octave -q ShipDistance.m 2>/dev/null)
grep "$shipname" shipsNAME-IMO.txt | cut -d "," -f 2 > IMO.txt
idnumber=$(cut -b 4-10 IMO.txt)
echo $idnumber,$dist
代码语言:javascript
复制
#!/bin/bash
rm -f shipsdist.csv
for ship in $(cat shipsNAME-IMO.txt | cut -d "," -f 1)
do
    ./FindShipDistance "$ship" >> shipsdist.csv
done
cat shipsdist.csv | sort | head -n 1
EN

回答 1

Stack Overflow用户

发布于 2022-01-14 19:37:48

提供的代码和错误消息表明,第二个脚本使用一个空的命令行参数调用第一个脚本。如果输入文件shipsNAME-IMO.txt包含任何空行,或者包含空第一个字段的任何行,则肯定会发生这种情况。开头或结尾的空行就能做到这一点。

我建议

  1. 使用read命令读取数据,并操作IFS来解析以逗号分隔的read输入和其他数据(通常是
  2. ),使脚本在发生可预测的故障时表现得更愉快。
  3. 更一般地使用Bash内部特性,而不是外部程序,因为前者相当自然。

G 212

例如:

代码语言:javascript
复制
#!/bin/bash

# Validate one command-line argument
[[ -n "$1" ]] || { echo empty ship name 1>&2; exit 1; }

# Read and validate an IMO corresponding to the argument
IFS=, read -r dummy imo tail < <(grep -F -- "$1" shipsNAME-IMO.txt)
[[ -f PerShip/"${imo}.csv" ]] || { echo no data for "'$imo'" 1>&2; exit 1; }

# Perform the distance calculation and output the result
cp PerShip/"${imo}.csv" tmpship.csv
dist=$(octave -q ShipDistance.m 2>/dev/null) ||
  { echo "failed to compute ship distance for '${imo}'" 2>&1; exit 1; }
echo "${imo:3:7},${dist}"

代码语言:javascript
复制
#!/bin/bash

# Note: the original shipsdist.csv will be clobbered

while IFS=, read -r ship tail; do
  # Ignore any empty ship name, however it might arise
  [[ -n "$ship" ]] && ./FindShipDistance "$ship"
done < shipsNAME-IMO.txt |
  tee shipsdist.csv |
  sort |
  head -n 1

注意,使管道的第二个脚本中的while循环成为管道的一部分将导致它在子subshell中运行。这有时是个难题,但在这种情况下不会造成任何问题。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70714217

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档