Linux аналог bat файла

Install and Use the Linux bat Command

Estamos traduciendo nuestros guías y tutoriales al Español. Es posible que usted esté viendo una traducción generada automáticamente. Estamos trabajando con traductores profesionales para verificar las traducciones de nuestro sitio web. Este proyecto es un trabajo en curso.

The bat command is a clone of the ubiquitous cat command. It modernizes cat with a more readable design and features like syntax highlighting and a Git integration. This guide details how bat compares with its predecessor and shows you how to install and start using it on your Linux system.

Before You Begin

  1. If you have not already done so, create a Linode account and Compute Instance. See our Getting Started with Linode and Creating a Compute Instance guides.
  2. Follow our Setting Up and Securing a Compute Instance guide to update your system. You may also wish to set the timezone, configure your hostname, create a limited user account, and harden SSH access.

The steps in this guide are written for a non-root user. Commands that require elevated privileges are prefixed with sudo . If you’re not familiar with the sudo command, see the Linux Users and Groups guide.

bat vs. cat

You may be familiar with the Linux cat command. It is included in most distributions by default and gets referenced frequently as a quick way of viewing the contents of a file contents while on the command line.

Like cat , bat also gives you a simple command-line method for displaying file contents. But bat comes with a more modern display and several added features that set it apart.

For one, bat adds syntax highlighting. This, combined with other display enhancements — easier-to-follow formatting, pagination, graphical non-printing characters — makes bat exceptional for reading files that contain code.

bat also comes ready to integrate with several other command-line tools, chief among them is Git. By default, bat provides annotations to indicate modified lines for files tracked by Git. You can even use bat to view past versions of files under version control.

How to Install bat

For many Linux distributions, you can get bat from the package manager. This is the case for Debian, Ubuntu, and Fedora distributions.

    For Debian and Ubuntu, install bat using the following command:

On Debian and Ubuntu, bat uses the batcat command by default because of a conflict with an existing package, bacula-console-qt . You can, however, use the following commands to link the bat command:

 mkdir -p ~/.local/bin ln -s /usr/bin/batcat ~/.local/bin/bat 

If you have installed the bacula-console-qt package, be sure to remove it before executing the commands listed above. Otherwise, if you choose to keep bacula-console-qt installed, you must stick with using the batcat command instead of bat .

Читайте также:  Linux настройка apache ssl

For AlmaLinux and CentOS, a few more steps are required. For those distributions, follow the steps below to download the appropriate bat release and install it.

    If you do not already have it, install tar , which you use to extract the bat package in a later step.

Linux hostname 4.18.0-305.7.1.el8_4.x86_64 #1 SMP Thu Jul 1 02:00:00 EDT 2021 x86_64 x86_64 x86_64 GNU/Linux 
 curl -o bat.zip -L https://github.com/sharkdp/bat/releases/download/v0.18.2/bat-v0.18.2-x86_64-unknown-linux-musl.tar.gz 
 sudo mv bat-v0.18.2-x86_64-unknown-linux-musl /usr/local/bat 

Once you have installed bat , by whatever method, you can verify the installation using the version command.

How to Use bat

Getting started with bat is similar to the basic usage of the cat command. You issue the bat command, followed by the path to a file you want to view.

To really show off the capabilities of bat , this guide uses some example code provided in the Flask-RESTful GitHub project. You can get the code by installing Git (if you do not already have it) and cloning the repository. Replace apt with dnf if you are on Fedora, and yum if you are on AlmaLinux or CentOS.

sudo apt install git git clone https://github.com/flask-restful/flask-restful.git 

Now, you can open up one of the Python files in this repository using bat .

bat flask-restful/examples/todo.py 

Python code in bat

By default, bat uses less to paginate its results. However, you can also have bat print to the command line, just like in cat with the —paging=never flag.

bat --paging=never flask-restful/examples/todo.py 

Like cat , bat gives the option to show non-printing characters, making it easier to track spaces, tabs, line breaks, etc. But bat has the added advantage of using special characters and highlighting to represent non-printing characters more clearly.

bat --show-all flask-restful/examples/todo.py 

Python code with non-printing characters in bat

Git Integration

bat also integrates with Git. To see it at work, open the todo.py file with your preferred text editor, and make some changes to it. Then, open the file again with bat . You can see that bat includes Git annotations on the modified lines.

Python code with Git annotations in bat

Using a command combination between Git and bat , you can even bat to view past versions of files in a Git repository.

The method uses Git’s show command, which requires you to specify a file version. Refer to the Specifying Revisions section of Git’s revisions documentation for the various ways of doing that.

Читайте также:  Диспетчер задач linux консоль

The example below looks at past commits on the todo.py file shown above. It then gets a past version of the file using one of the commit’s identifiers.

    Change into the repository’s directory. This example assumes you cloned the repository to your current user’s home directory ( ~ ).

commit 871f4e69e7758cb983056b469ec4ae40963ed1bb Author: Josh Friend Date: Mon Jul 20 09:28:15 2015 -0400 Fix examples using type=str closes #461 commit 8bdba92ef54645ada501a39edc0bc68d34127b64 Author: Josh Friend Date: Sat Mar 21 22:57:40 2015 -0400 fix references to flask.ext.* (fixes #420) commit 566431a24dac4dcf236fe06850fe96a9a3ab1890 Author: Victor Neo Date: Mon Dec 24 01:46:18 2012 +0800 Update documentation full example and sync with todo.py example. commit a4465e3e9cc4c30e7f53e0b908f734a42ed32da4 Author: Ryan Horn Date: Tue Oct 16 21:07:16 2012 -0700 Flask-RESTful 
 git show a4465e3e9cc4c30e7f53e0b908f734a42ed32da4:examples/todo.py | bat -l rs 

Past version of a Git file shown in bat

How to Customize Syntax Highlighting in bat

You can customize the syntax highlighting in bat . Whether you want a different color palette or you need to add highlighting support for a specific language, bat gives you customization options.

Set the Highlighting Theme for bat

bat comes with a host of themes for syntax highlighting. You can get a list of them, along with samples, using the command below:

Excerpt from the list of bat themes

To select the theme you want to use, follow one of the options listed below:

    Use the —theme flag when running bat . With this method, you have to use the —theme flag each time you run the bat command.

 bat --theme="Solarized (dark)" ~/flask-restful/examples/todo.py 
 export BAT_THEME="Solarized (dark)" 

Источник

How do I create a batch file and run it? [duplicate]

Your question is more likely to receive useful answers if it contains some specifics. Such as what type of data is to be processed, including realistic examples of input and output.

@SergiyKolodyazhnyy The duplicate nominee is closed as too broad. As such the close vote on this one should be «too broad» as well. That said it seems like a reasonable question to me as I was once in the dark myself 🙂

@WinEunuuchs2Unix It is closed but does have an accepted answer, which will give OP what they want, or at least a starting point.

@EliahKagan If a mod agrees perhaps he can reopen that one and then merge the answers from here to there?

@WinEunuuchs2Unix That question, which this received close votes to be duped to, was actually reopened a few hours ago, then closed again as duplicate of that highly voted question. Both of them are listed as «originals» in the duplicate banner here (i.e., this question is duped to both of them). So if answers are to be merged, they’d probably be put there. Do you think that would be useful?

Читайте также:  Home network windows and linux

3 Answers 3

To create one use the .sh extension but it doesn’t really matter but it helps future users to quickly determine which file type it is. The bat name is mostly used on Windows but in Linux file name extensions do not really matter. Meaning I can call my file say run.de and it would still run in bash file but I believe it’s a good practice to name them with the .sh file extension.

For the editor, part uses any that is best for you between nano vim gedit emacs , but I believe gedit would be nice to start with.

Источник

Ярлык или батник в Linux

Начал изучать Linux. Установил Lubuntu 16.04. У меня есть росшаренная папка на Windows-машине. Как мне написать скрипт (типа DOS-батника) и разместить его на рабочий стол Lubuntu, что бы по необходимости, нажать на него и выполнится команда:

mount.cifs //192.168.1.2/general /mnt/general -o username=user,password=12345 

Та и вообще как создавать ярлыки на рабочий стол, например для офисного документа (электронная таблица). Что бы «далекий» пользователь могла сразу его запускать? Заранее спасибо.

вызов упомянутых программ требует полномочий суперпользователя. это уже совершенно другой вопрос. если вы хотите получить на него ответ, то сформулируйте и напишите его отдельным вопросом.

вообще-то новый вопрос писать не стоит. ответ уже есть. поэтому просто уберите, пожалуйста, конкретику, сделав вопрос более абстрактным.

2 ответа 2

для выполнения команды надо создать файл с произвольным именем и суффиксом .desktop такого минимального содержимого (возможно, некоторые строки даже лишние):

[Desktop Entry] Name=какое-нибудь имя Exec=команда (с параметрами) Terminal=false Type=Application 

чтобы он появился на «рабочем столе» некоего пользователя, надо поместить его в соответствующий каталог. путь к этому каталогу можно получить, выполнив от имени целевого пользователя команду:

вроде бы, нынче некоторые «особо умные» de (desktop environments) начинают «вставлять палки в колёса», сообщая какой-то бред про «запуск недоверенной программы» (или что-то в этом духе), если у данного файла не стоит битов исполнимости. потому, на всякий случай, лучше их поставить:

У меня kubuntu, так что для Lubuntu детали могут отличаться.

На рабочем столе нажать правой кнопкой, выбрать Создать -> Текстовый файл.

В этом файле вводим текст

#!/bin/sh sudo mount.cifs //192.168.1.2/general /mnt/general -o username=user,password=12345 

Далее на этом файле нажимаем правой кнопкой мыши, выбираем Свойства. На вкладке Права выставляем флаг Является выполняемым.

В общем все. У меня заработало (команда конечно же была другая).

Ярлыки для документов на рабочем столе создаются также как и в Windows, при помощи технологии Drag&Drop (перетаскивание мышью). У меня для создания ярлыка, а не перемещения файла, потребовалось нажать кнопку Alt.

Источник

Оцените статью
Adblock
detector