Table of Contents
显示动画以指示长时间运行的任务" >显示动画以指示长时间运行的任务
从Bash显示本地GUI通知" >从Bash显示本地GUI通知
在Bash脚本中的多进程处理" >在Bash脚本中的多进程处理
使用Bash显示GUI组件
使用文本样式现代化终端输出" >使用文本样式现代化终端输出
Home Operation and Maintenance Nginx Five Little-Known Modern Bash Scripting Techniques

Five Little-Known Modern Bash Scripting Techniques

Jun 26, 2023 pm 08:36 PM
Script bash

Bash命令语言常被程序员用来编写Shell脚本,以实现手动任务的自动化。他们会编写Bash脚本来自动化各种配置、文件操作、构建结果生成和与DevOps相关的活动。几乎所有类Unix或基于Unix的操作系统都为用户提供预安装的Bash解释器,因此我们可以使用Bash编写更具可移植性的自动化脚本。

正如我们已经知道的那样,Bash脚本编写是指使用Bash命令语言的语法、内置Bash命令和核心操作系统CLI程序(如GNU核心工具)编写一系列命令。一般而言,遵循传统的Bash脚本会执行一些命令并在终端上输出纯文本。

我们可以使用几个特别的理念来使我们的 Bash 脚本更加适用于未来且更加用户友好。使用一些不太常见的现代Bash脚本编写技巧,可以令您的自动化脚本更具现代感,涵盖以下概念。

五个鲜为人知的现代 Bash 脚本编写技术

显示动画以指示长时间运行的任务

在某些情况下,我们需要从Bash脚本中执行长时间运行的命令。有几种方法可以指示长时间运行的任务。显示带有三个点的消息(也称为省略号),最简单和最容易的方法是使用echo命令。然而,这种技术所产生的信息是静态的,缺乏互动性和用户友好性,对于开发人员也是如此。

轻松展示ASCII动画只需使用核心Unix操作系统命令和Bash内置命令即可。看下面这个只有两个动画帧的简单动画示例:

#!/bin/bash# Linux迷 www.linuxmi.comwhile true;do# Frame #1printf "\r< Loading..." sleep 0.5# Frame #2 printf "\r> Loading..." sleep 0.5 done
Copy after login

上面的Bash脚本在终端上显示一个无尽的两帧动画。printf语句使用\r转义字符来重置当前行的终端光标。上面的脚本呈现了以下基于文本的动画:

五个鲜为人知的现代 Bash 脚本编写技术

一个简单的两帧文本动画

我们可以在动画中添加更多帧,并使用以下Bash脚本在特定耗时任务完成之前一直显示动画。

#!/bin/bash# Linux迷 www.linuxmi.comsleep 5 &pid=$!frames="/ | \\ -"while kill -0 $pid 2&>1 > /dev/null;dofor frame in $frames;doprintf "\r$frame Loading..."sleep 0.5donedoneprintf "\n"
Copy after login

该脚本将显示一个基于文本的旋转器动画,直到经过5秒的sleep命令完成执行。同样地,我们可以使用旋转器动画来代替静态消息,在执行任何需要耗时的任务时显示。预览如下。

五个鲜为人知的现代 Bash 脚本编写技术

一个带有旋转器文本动画的Bash脚本,作者的截图 这些基于文本的动画使命令行程序更加用户友好和互动,因此大多数现代命令行程序都显示这些ASCII动画。现在你知道如何通过改变帧字符列表,为你的Bash脚本添加动画效果。

从Bash显示本地GUI通知

常用的开发人员通常会使用Bash脚本和命令行程序来提供工具的终端界面。例如,Flutter框架为开发人员提供了flutter命令行程序,用于管理Flutter应用程序和配置Flutter应用程序开发环境。假设你正在开发一个耗时的命令行脚本。在用户不查看终端输出时,如何显示重要消息?

GUI通知在所有Unix类和基于Unix的操作系统中都可以使用特定的命令来显示。我们可以从Bash脚本中调用这些命令来显示本地通知。比如,在以GNU/Linux为基础的操作系统上,你可以使用notify-send命令,示例如下:。

#!/bin/bash# Linux迷 www.linuxmi.comsleep 10notify-send "notify.sh" "Task #1 已成功完成 www.linuxmi.com"
Copy after login

一些GNU/Linux发行版通常会预装notify-send工具的版本。上面的Bash脚本在十秒后显示了一个本地通知。预览如下:

五个鲜为人知的现代 Bash 脚本编写技术

在Ubuntu上的本地通知截图

macOS用户可以通过在Bash中执行AppleScript解释器来显示本地通知,如下所示:

#!/bin/bashsleep 10osascript -e "display notification \"Task #1 www.linuxmi.com 已成功完成\" with title \"notify.sh\""
Copy after login

在Bash脚本中的多进程处理非常有助于通过长时间运行的脚本或永久运行的后台脚本向用户通知重要事件。

在Bash脚本中的多进程处理

通常,程序员使用Bash脚本按顺序运行命令。所以,Bash解释器会一个接一个地运行每个语句,直到到达源文件的结尾或遇到一个exit语句。然而,我们可以改变这种顺序执行的方式,实现并行执行以加快自动化脚本的速度。

我们可以将整个 Bash 脚本分成几个独立的函数,从而让每个函数可以异步运行。接下来,我们可以将所有Bash函数作为后台任务运行。最后,我们可以使用内置的wait命令来保持脚本执行过程处于活动状态,直到所有异步进程执行结束。

请看以下示例代码:

#!/bin/bash# Linux迷 www.linuxmi.comfunction task1() {echo "Running task1..."sleep 5}function task2() {echo "Running task2..."sleep 5}task1 &task2 &waitecho "www.linuxmi.com 全部完成"
Copy after login

在这个例子中,我们将两个并行函数task1和task2作为后台任务运行。我们还使用了内置的wait命令来确保脚本实例保持活动状态,直到后台任务完成执行。如果你检查脚本的执行时间,你会发现这两个函数在大约五秒钟内结束,而不是十秒钟。

五个鲜为人知的现代 Bash 脚本编写技术

使用Bash显示GUI组件

我们之前探讨了如何使用Bash脚本运行一段时间后显示GUI通知。同样地,我们可以展示其他的GUI组件,例如提示框、文本框和文件选择器。有时我们需要为非技术人员创建基于GUI的自动化程序。如果你已经了解Bash脚本编写,你不需要使用其他GUI开发工具来创建简单的GUI应用程序——因为我们可以使用Bash显示GUI元素。

zenity程序提供了几个命令,用于在GNU/Linux命令行环境中显示各种GUI元素。例如,我们可以使用以下命令打开文件选择对话框。

zenity --file-selection
Copy after login

Zenity版本通常预装在大多数基于GNOME的GNU/Linux操作系统发行版中。此外,作为替代,你可以在基于KDE的GNU/Linux发行版中使用kdialog命令。

macOS用户可以像往常一样调用AppleScript解释器。例如,他们可以使用以下命令通过Bash脚本显示文件选择对话框。

osascript -e "POSIX path of (choose file)"
Copy after login

你也可以像Zenity那样构建自己的二进制文件,并从Bash脚本中显示任何GUI组件。此外,你还可以使用Neutralinojs通过Bash脚本在本地/远程窗口中显示交互式的HTML界面。

使用文本样式现代化终端输出

我们经常使用echo命令输出脚本中的消息。默认情况下,echo命令根据默认终端文本样式打印给定的文本。在特定情况下,我们可以根据当前环境应用基本的用户体验原则来提升文本样式。例如,我们可以使用红色显示错误消息。此外,您可以使用粗体字体样式强调段落中的一些关键细节。

tput是一个Unix程序,提供控制当前终端屏幕的命令。它提供了改变终端光标位置、获取终端信息和更改文本样式的命令。我们可以将tput命令与echo命令结合使用,在所有类Unix和基于Unix的操作系统上打印各种文本样式。

请看以下示例,打印不同的文本样式:

#!/bin/bash# Linux迷 www.linuxmi.combold=$(tput bold)underline=$(tput smul)italic=$(tput sitm)info=$(tput setaf 2)error=$(tput setaf 160)warn=$(tput setaf 214)reset=$(tput sgr0)echo "${info}INFO${reset}: This is an ${bold}info${reset} message"echo "${error}ERROR${reset}: This is an ${underline}error${reset} message"echo "${warn}WARN${reset}: This is a ${italic}warning${reset} message"
Copy after login

在这里,我们使用tput命令为每种文本样式定义了一些变量。最后,我们使用echo命令执行临时保存的命令,以显示不同的文本样式,如下所示。

五个鲜为人知的现代 Bash 脚本编写技术

Bash中的文本样式屏幕截图

您可以使用上述方法为Bash脚本构建自己的个性化颜色方案。为了掩盖kill命令的错误消息,上述代码示例使用了空设备文件(/dev/null)。

The above is the detailed content of Five Little-Known Modern Bash Scripting Techniques. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Python script to be executed every 5 minutes Python script to be executed every 5 minutes Sep 10, 2023 pm 03:33 PM

Automation and task scheduling play a vital role in streamlining repetitive tasks in software development. Imagine there is a Python script that needs to be executed every 5 minutes, such as getting data from an API, performing data processing, or sending periodic updates. Running scripts manually so frequently can be time-consuming and error-prone. This is where task scheduling comes in. In this blog post, we will explore how to schedule a Python script to execute every 5 minutes, ensuring it runs automatically without manual intervention. We will discuss different methods and libraries that can be used to achieve this goal, allowing you to automate tasks efficiently. An easy way to run a Python script every 5 minutes using the time.sleep() function is to utilize tim

How to execute .sh file in Linux system? How to execute .sh file in Linux system? Mar 14, 2024 pm 06:42 PM

How to execute .sh file in Linux system? In Linux systems, a .sh file is a file called a Shell script, which is used to execute a series of commands. Executing .sh files is a very common operation. This article will introduce how to execute .sh files in Linux systems and provide specific code examples. Method 1: Use an absolute path to execute a .sh file. To execute a .sh file in a Linux system, you can use an absolute path to specify the location of the file. The following are the specific steps: Open the terminal

How to create a script for editing? Tutorial on how to create a script through editing How to create a script for editing? Tutorial on how to create a script through editing Mar 13, 2024 pm 12:46 PM

Cutting is a video editing tool with comprehensive editing functions, support for variable speed, various filters and beauty effects, and rich music library resources. In this software, you can edit videos directly or create editing scripts, but how to do it? In this tutorial, the editor will introduce the method of editing and making scripts. Production method: 1. Click to open the editing software on your computer, then find the "Creation Script" option and click to open. 2. In the creation script page, enter the "script title", and then enter a brief introduction to the shooting content in the outline. 3. How can I see the "Storyboard Description" option in the outline?

Python script to shut down computer Python script to shut down computer Aug 29, 2023 am 08:01 AM

In today's fast-paced digital world, being able to automate computer tasks can greatly increase productivity and convenience. One of the tasks is shutting down the computer, which can be very time-consuming if done manually. Thankfully, Python provides us with a powerful set of tools to interact with the system and automate such tasks. In this blog post, we will explore how to write a Python script to shut down your computer easily. Whether you want to schedule an automatic shutdown, remotely initiate a shutdown, or simply save time by avoiding a manual shutdown, this script will come in handy. Importing the Required Modules Before we start writing the script, we need to import the necessary modules in order to interact with the system and execute the shutdown command. In this section we will import the os module (which

Python script to restart computer Python script to restart computer Sep 08, 2023 pm 05:21 PM

Restarting your computer is a common task that we often perform to troubleshoot problems, install updates, or apply system changes. While there are many ways to restart your computer, using a Python script provides automation and convenience. In this article, we will explore how to create a Python script that can restart your computer with a simple execution. We will first discuss the importance of restarting your computer and the benefits it brings. We will then delve into the implementation details of the Python script, explaining the necessary modules and functionality involved. Throughout this article, we will provide detailed explanations and code snippets to ensure clear understanding. Importance of Restarting Your Computer Restarting your computer is a basic troubleshooting step that can

Python script packaging exe, auto-py-to-exe will help you! Python script packaging exe, auto-py-to-exe will help you! Apr 13, 2023 pm 04:49 PM

1. What is auto-py-to-exeauto-py-to-exe is a graphical tool used to package Python programs into executable files. This article mainly introduces how to use auto-py-to-exe to complete python program packaging. auto-py-to-exe is based on pyinstaller. Compared with pyinstaller, it has an additional GUI interface and is simpler and more convenient to use. 2. To install auto-py-to-exe, first we must ensure that our python environment is greater than or equal to 2.7 Then enter in cmd: pip install

Different ways to run shell script files on Windows Different ways to run shell script files on Windows Apr 13, 2023 am 11:58 AM

Windows Subsystem for Linux The first option is to use Windows Subsystem for Linux or WSL, which is a compatibility layer for running Linux binary executables natively on Windows systems. It works for most scenarios and allows you to run shell scripts in Windows 11/10. WSL is not automatically available, so you must enable it through your Windows device's developer settings. You can do this by going to Settings > Update & Security > For Developers. Switch to developer mode and confirm the prompt by selecting Yes. Next, look for W

Super hardcore! 11 very practical Python and Shell script examples! Super hardcore! 11 very practical Python and Shell script examples! Apr 12, 2023 pm 01:52 PM

Some examples of Python scripts: enterprise WeChat alarms, FTP clients, SSH clients, Saltstack clients, vCenter clients, obtaining domain name SSL certificate expiration time, sending today's weather forecast and future weather trend charts; some examples of Shell scripts: SVN Full backup, Zabbix monitoring user password expiration, building local YUM, and the readers' needs in the previous article (when the load is high, find out the process scripts with high occupancy and store or push notifications); it is a bit long, so please read it patiently At the end of the article, there is an Easter egg after all. Python script part of enterprise WeChat alarm This script uses enterprise WeChat application to perform WeChat alarm and can be used

See all articles