【问题标题】:Is there a way to loop opening a specific website in bash?有没有办法在 bash 中循环打开特定网站?
【发布时间】:2020-05-08 15:32:13
【问题描述】:

我试图编写一个脚本来打开文本文件中的所有网页。我到目前为止是这样的:

#!bin/bash
num=1

while [ $num -lt 4 ];
do
    site=$(sed -n $num{p} endingtext.txt | cut -d " " -f2)
    google-chrome https://www.exampl.com$site
    ((num++))
done

我的文本文件如下所示:

Disallow: /example1
Disallow: /example2
Disallow: /example3
Disallow: /example4
etc...

这个脚本的问题是在打开其中一个网页后它会停止循环。我想知道是否有可能让它继续循环

【问题讨论】:

  • 您的脚本停止循环,因为 Google Chrome 没有与运行脚本的进程分离。您可能可以使用google-chrome "https://www.exampl.com$site" & 在后台启动 Google Chrome。我还强烈建议您修复脚本中所有缺失的双引号。

标签: bash loops


【解决方案1】:

我可以在我的 Mac 上执行此操作,而且效果非常好:

#!/bin/bash

site='https://www.example.com'
for n in ${site}'/example'{1..3}
do
    open -a "Google Chrome" "${n}"
done

希望对你有用。

【讨论】:

    【解决方案2】:

    修复了脚本的问题:

    1. #!bin/bash

      Shebang 必须是绝对路径。它错过了领先的/

      正确的社帮是:#!/bin/bash

    2. 第 4 行:while [ $num -lt 4 ];:

      循环关闭 1,因为它会在 $num 等于 4 时停止,并且由于它从 1 开始,因此只会运行输入文件的前三行。

    3. 第 6 行:site=$(sed -n $num{p} endingtext.txt | cut -d " " -f2)

      1. 花括号{} 需要为shell 转义。
        正确的转义是:site=$(sed -n $num\{p\} endingtext.txt | cut -d " " -f2)

      2. 要么使用双引号"
        正确的引用是:site=$(sed -n "$num{p}" endingtext.txt | cut -d " " -f2)

    4. 第 7 行:google-chrome https://www.exampl.com$site

      还缺少双引号 " 以防止文件模式扩展 (GLOB)。
      正确的引用是:google-chrome "https://www.exampl.com$site"

    现在所有这些sedcut 调用在这里重新读取每一行的整个输入文件,最终执行顺序行访问;可以通过使用 POSIX 标准 read 命令大大简化。

    #!/usr/bin/env sh
    
    num=1
    while [ $num -le 4 ] && read -r _ site;
    do
        google-chrome "https://www.example.com$site" &
        num=$((num+1))
    done < endingtext.txt
    

    或者一个紧凑的形式:

    <endingtext.txt cut -d: -f2- | xargs -l -exec bash -c 'google-chrome "https://www.example.com$site$0" &'
    

    【讨论】:

      猜你喜欢
      • 2022-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 2023-03-06
      • 2023-02-09
      相关资源
      最近更新 更多