首页 > 解决方案 > 有没有办法在 bash 中循环打开特定网站?

问题描述

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

#!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...

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

标签: bashloops

解决方案


修复了脚本的问题:

  1. #!bin/bash

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

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

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

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

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

    1. 任何一个花括号{}都需要为外壳转义。
      正确的转义是: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" &'

推荐阅读