Repository: alexanderepstein/Bash-Snippets Branch: master Commit: 581a6b4ea681 Files: 66 Total size: 376.9 KB Directory structure: gitextract_7784tk_y/ ├── .github/ │ ├── FUNDING.yml │ ├── ISSUE_TEMPLATE.md │ ├── PULL_REQUEST_TEMPLATE.md │ ├── stale.yml │ └── workflows/ │ └── shellcheck.yml ├── .gitignore ├── .travis.yml ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── bak2dvd/ │ └── bak2dvd ├── bash-snippets/ │ └── bash-snippets ├── bash-snippets.1 ├── bash-snippets.1.html ├── bash-snippets.1.ronn ├── changelog.md ├── cheat/ │ └── cheat ├── cloudup/ │ └── cloudup ├── crypt/ │ └── crypt ├── cryptocurrency/ │ └── cryptocurrency ├── currency/ │ └── currency ├── extras/ │ ├── Linux/ │ │ └── maps/ │ │ └── maps │ └── README.md ├── geo/ │ └── geo ├── gist/ │ ├── README.md │ └── gist ├── install.sh ├── lyrics/ │ └── lyrics ├── meme/ │ └── meme ├── movies/ │ ├── movies │ └── tmdb ├── newton/ │ └── newton ├── pwned/ │ └── pwned ├── qrify/ │ └── qrify ├── short/ │ └── short ├── siteciphers/ │ └── siteciphers ├── skeleton ├── skeleton.bats ├── stocks/ │ └── stocks ├── taste/ │ └── taste ├── tests/ │ ├── bak2dvd.bats │ ├── cheat.bats │ ├── cloudup.bats │ ├── crypt.bats │ ├── cryptocurrency.bats │ ├── currency.bats │ ├── geo.bats │ ├── gist.bats │ ├── meme.bats │ ├── movies.bats │ ├── newton.bats │ ├── qrify.bats │ ├── short.bats │ ├── siteciphers.bats │ ├── stocks.bats │ ├── taste.bats │ ├── todo.bats │ ├── transfer.bats │ ├── weather.bats │ └── ytview.bats ├── todo/ │ └── todo ├── transfer/ │ └── transfer ├── uninstall.sh ├── weather/ │ └── weather └── ytview/ └── ytview ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/FUNDING.yml ================================================ # These are supported funding model platforms github: [alexanderepstein] ================================================ FILE: .github/ISSUE_TEMPLATE.md ================================================ **Issue Label:** * [ ] Bug * [ ] New feature * [ ] Enhancement * [ ] New component **Description:** ### If its a bug make sure to include this section. **OS and OS version:** * [ ] Mac * [ ] Linux 32 Bit * [ ] Linux 64 Bit * [ ] Windows 32 Bit * [ ] Windows 64 Bit OS Version: ================================================ FILE: .github/PULL_REQUEST_TEMPLATE.md ================================================ **Pull Request Label:** * [ ] Bug * [ ] New feature * [ ] Enhancement * [ ] New component * [ ] Typo **Pull Request Checklist:** - [ ] Have you followed the [guidelines for contributing](https://github.com/alexanderepstein/Bash-Snippets/blob/master/CONTRIBUTING.md)? - [ ] Have you checked that there aren't other open [pull requests](https://github.com/alexanderepstein/Bash-Snippets/pulls) for the same fix or component? - [ ] Have you ran the tests locally with `bats tests`? ----- ================================================ FILE: .github/stale.yml ================================================ # Number of days of inactivity before an issue becomes stale daysUntilStale: 175 # Number of days of inactivity before a stale issue is closed daysUntilClose: 5 # Issues with these labels will never be considered stale exemptLabels: - New Component # Label to use when marking an issue as stale staleLabel: Stale # Comment to post when marking an issue as stale. Set to `false` to disable markComment: > This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions. # Comment to post when closing a stale issue. Set to `false` to disable closeComment: > This issue has been automatically closed because it has been inactive for 180 days. ================================================ FILE: .github/workflows/shellcheck.yml ================================================ on: push jobs: shellcheck: name: Shellcheck runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Run ShellCheck uses: ludeeus/action-shellcheck@master ================================================ FILE: .gitignore ================================================ # IDE .idea # Meta files .DS_Store Thumbs.db ================================================ FILE: .travis.yml ================================================ language: bash matrix: include: - os: linux dist: trusty sudo: required - os: osx allow_failures: - os: linux before_install: - sudo ./install.sh all - export TASTE_API_KEY='290044-Taste-QIQUQKOZ' install: - if [ $TRAVIS_OS_NAME = linux ]; then sudo add-apt-repository ppa:duggan/bats --yes; fi - if [ $TRAVIS_OS_NAME = linux ]; then sudo apt-get update; fi - if [ $TRAVIS_OS_NAME = linux ]; then sudo apt-get install -qq bats; else brew install bats; fi - if [ $TRAVIS_OS_NAME = linux ]; then sudo apt-get install -qq openssl; else brew install openssl; fi script: - bats tests ================================================ FILE: CODE_OF_CONDUCT.md ================================================ # Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at epsteina@wit.edu. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/ ================================================ FILE: CONTRIBUTING.md ================================================ # Contributing ### First off, thank you for considering contributing to Bash-Snippets. #### Where do I go from here? If you've noticed a bug or have a question, search the issue tracker to see if someone else in the community has already created a ticket. If not, go ahead and make one! #### Otherwise if implementing a fix, feature or new component go through these steps #### 1. Fork & Clone The Repository * Fork the repository * It is assumed you are on either a Unix or Linux system in which are there are no dependencies * To download the full source code after forking ```bash git clone https://github.com/yourusernamehere/Bash-Snippets ``` #### 2. Implement your fix, feature or new component ###### Fix/Feature At this point, you're ready to make your changes! ###### New Component * Decide on a short but sweet name for your tool * Create a folder in the Bash-Snippets root directory named after the tool * Copy over the Bash-Snippets tool [skeleton](https://github.com/alexanderepstein/Bash-Snippets/blob/master/skeleton) to the newly created folder * Rename the skeleton in the new directory to the name of the tool * Using newly copied over file as a basis (with the name of your tool) code your new component! Feel free to ask for help; everyone is a beginner at first :smile_cat: Make sure to make your commit messages informative and concise. #### 3. Check The Script Runtime If you changed the weather script for example try running it and see if it works as intended. Run ```bats tests``` when inside the Bash-Snippets directory to test the tools. If you added a new script/tool test it to see if it works. #### 4. Create A Pull Request First make sure to commit and push your changes to your forked repository. Check to see if there are any conflicts with the main repository and your fork. If there are none submit the request and give details as to what you changed or added. #### 5. Bask In All The Glory Of Adding To A FOSS Application ![Had to do it to em](https://68.media.tumblr.com/2dfc3369827df9b981e111d7fd8fc732/tumblr_mvemcyarmn1rslphyo1_400.gif) ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2017 Alex Epstein Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================
# Bash-Snippets ##### A collection of small bash scripts for heavy terminal users with no dependencies ![Version](https://img.shields.io/github/release/alexanderepstein/Bash-Snippets.svg) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/a4bf023a3d0d499abc9d2bf14b296a14)](https://www.codacy.com/app/alexanderepstein/Bash-Snippets?utm_source=github.com&utm_medium=referral&utm_content=alexanderepstein/Bash-Snippets&utm_campaign=Badge_Grade) [![Build Status](https://travis-ci.org/alexanderepstein/Bash-Snippets.svg?branch=master)](https://travis-ci.org/alexanderepstein/Bash-Snippets) ![platform](https://img.shields.io/badge/platform-OSX%2C%20Linux%20%26%20Windows-blue.svg) [![license](https://img.shields.io/github/license/mashape/apistatus.svg?style=plastic)]() ### All of these scripts have been heavily tested on macOS and Linux ### Most of these scripts have been tested on Windows 10 and the official developer bash instance. Does not work with Cygwin or Mysys2. #### Looking for maintainers: I have been and probably will forever be too busy to maintain this properly on my own. I am looking for a few others to help out, if you want to be a maintainer either email me or raise an issue. I will probably only accept maintainers who have made a few contributions (no matter how small) and seem to understand the vision of this project.
## Tools
Cheat The fastest way to find {command options|code pieces} you need Supports multiple languages and many bash commands
Cloudup A tool that facilitates backing up github repositories to bitbucket If you have ever felt the fear of the github unicorn this could be your savior Furthermore you can backup the repositories of any github user to your bitbucket. Backup all github repositories of the designated user at once with the -a option. Or run it with no flags and backup individual repositories.
Crypt A wrapper for openssl that allows for quickly encrypting and decrypting files ```bash crypt -e [original file] [encrypted file] # encrypts files crypt -d [encrypted file] [output file] # decrypts files ``` #### Encryption Details * Uses AES 256 level encryption * Key is salted before creation * Password is never in plain text, and OpenSSL generates key based on password * Encrypted data is encoded in Base64, so it can be used as plain text in an email. (Not usually necessary if attached as a file) **Tested With** .pdf, .txt, .docx, .doc, .png, .jpeg **CAUTION** Make sure to use different filenames, otherwise your file will be overwritten!
Cryptocurrency Converts Cryptocurrency based on realtime exchange rates of the top 10 cryptos
Originally written by: [Jonas-Taha El Sesiy](https://github.com/elsesiy) Heavy modifications by: [Alex Epstein](https://github.com/alexanderepstein)
Currency Converts currency based on realtime exchange rates
If you want to bypass to guided input you can pass in 3 arguments and it will run from there ex.```currency [baseCurrency] [exchangeToCurrency] [amountBeingExchanged]``` so a valid use case would be ```currency USD EUR 12.35```
Geo Provides data for wan, lan, router, dns, mac, and ip geolocation
Written by: [Jake Meyer](https://github.com/jakewmeyer)
Gist Manage your gist like a pro Clone your owned gists and starred gists as git repos, and Fetch/Create/Edit/Delete them with Github API. It also supports quick search with hashtag and contents. For more information, please go through the [guide](gist/README.md)
Written by: [typebrook](https://github.com/typebrook)
Lyrics Grab lyrics for a given song quickly from the command line.
Meme A lightning fast meme generator.
Movies Quick search that grabs relevant information about a movie
Newton Performs numerical calculations all the way up to symbolic math parsing.
Qrify Takes any string of text and turns it into a qr code This is useful for sending links or saving a string of commands to your phone
Written by: [Linyos Torovoltos](http://github.com/linyostorovovoltos)
Short Gets the link that is being masked by a url shortner
Siteciphers Check which ciphers are enabled / disabled for a given https site. Sometimes ciphers are deemed vulnerable, so when you are changing configuration, this can be used to confirm that the cipher truly is disabled. Some browsers (For example old versions of IE) don't support some of the newer ciphers, which would be a good example of when a SysAdmin would need a list of currently supported ciphers so that changes can be made.
Stocks Provides information about a certain stock symbol
Taste Recommendation engine that provides three similar items like the supplied item Also can provide information on a given item Valid items are: shows, books, music, artists, movies, authors, games
### Needs an API Key (don't worry it's free) * Get the API key [here](https://tastedive.com/account/api_access) * After getting the API key run the following line ```export TASTE_API_KEY="yourAPIKeyGoesHere" >> ~/.bash_profile```
Todo A simplistic command line todo list
Transfer Quickly transfer files from the command line.
Weather Provides a 3 day forecast With no arguments it will grab the weather for your location as determined by your ip
With arguments you can pass in a city or country and get the weather in that area Also can show the current moon phase
Youtube-Viewer Provides a way to watch youtube videos from the terminal. You can use ```ytview -c [channel name]``` to see recent videos by that artist. You can use ```ytview -s [videoToSearch]``` or just ```ytview [videoToSearch]``` to search for videos.
Written by: [Linyos Torovoltos](http://github.com/linyostorovovoltos)
## API's Used
All API's * To get location based on ip address: [ipinfo](https://ipinfo.io) * To get and print weather based on a location: [wttr](http://wttr.in) * To grab the stock information in JSON format: [alphavantage](https://www.alphavantage.co) * To grab the latest exchange rate between currencies: [fixer](http://fixer.io) * To grab information on movies: [omdbapi](http://www.omdbapi.com/) * To grab recommendations based on an item: [tastedive](https://tastedive.com) * To determine masked link behind url shortner: [ki.tc](http://ki.tc) * To grab cheatsheets for commands and languages: [cheat](http://cheat.sh/) * To encode text into a qr code: [qrenco](http://qrenco.de) * To grab a list of a users repositories: [github](https://developer.github.com/v3/) * To upload a repository to bitbucket: [bitbucket](https://developer.atlassian.com/bitbucket/api/2/reference/) * To get your WAN ip address: [ipify](https://www.ipify.org/) * To grab the latest exchange rate between cryptocurrencies to standard currencies: [coinmarketcap](https://coinmarketcap.com/api/) * To perform symbolic math and other computations: [newton](https://newton.now.sh) * To transfer files: [transfer](https://transfer.sh) * To grab lyrics from a song: [lyrics.ovh](http://docs.lyricsovh.apiary.io) * To generate memes: [MemeGen](https://memegen.link) * To get a chart of the top 10 cryptocurrencies [rate.sx](http://rate.sx)
## Installing [![Packaging status](https://repology.org/badge/vertical-allrepos/bash-snippets.svg)](https://repology.org/project/bash-snippets/versions)
AUR bash-snippets is available in two different AUR packages: `bash-snippets` and `bash-snippets-git`. ```bash yay -S bash-snippets # or bash-snippets-git ```
APT Package Manager ```bash sudo add-apt-repository ppa:navanchauhan/bash-snippets # add bash-snippets PPA sudo apt update # update package list sudo apt install bash-snippets # install bash-snippets package ```
homebrew (macOS) / linuxbrew (Linux) ```bash brew install bash-snippets # installs all tools brew install bash-snippets --without-all-tools --with-newton --with-weather # specifying install for individual tools ```
From Source ```bash git clone https://github.com/alexanderepstein/Bash-Snippets # clone the repository cd Bash-Snippets # cd into the cloned directory git checkout v1.23.0 # Git checkout to the latest stable release ``` ```bash ./install.sh all # install all scripts ``` or ```bash ./install.sh stocks # to install individual scripts ```
## Updating
AUR ```bash yay -S bash-snippets # or bash-snippets-git ```
APT Package Manager ```bash sudo apt update # update package list sudo apt upgrade bash-snippets # upgrade bash-snippets package ```
homebrew (macOS) / linuxbrew (Linux) ```bash brew install bash-snippets --without-all-tools --with-newton --with-weather # specifying install for individual tools ```
From Source With any of the installed tools you can automate the update by running it with the -u option or passing in update as the arguments Ex. `stocks update` or `stocks -u` This will clone the repository and install the new versions of scripts that were installed, if you didn’t install a certain tool this script will not install the new version of that tool.
## Uninstalling
AUR ```bash pacman -Rns bash-snippets # or bash-snippets-git ```
APT Package Manager ```bash sudo apt purge bash-snippets # you can also use remove instead of purge ```
homebrew (macOS) / linuxbrew (Linux) ```bash brew uninstall bash-snippets ```
Git Uninstall ```bash git clone https://github.com/alexanderepstein/Bash-Snippets # If you don't have the Bash-Snippets folder anymore clone the repository cd Bash-Snippets # cd into the Bash-Snippets directory: ```
To go through a guided uninstall ```bash ./uninstall.sh ``` ##### To uninstall all installed bash-snippets ```bash ./uninstall.sh all ``` ##### To go through a guided uninstall ```bash ./uninstall.sh ``` ##### To uninstall all installed bash-snippets ```bash ./uninstall.sh all ```
## Donate If this project helped you in any way and you feel like supporting me [![Donate](https://img.shields.io/badge/Donate-Venmo-blue.svg)](https://venmo.com/AlexanderEpstein) [![Donate](https://img.shields.io/badge/Donate-SquareCash-green.svg)](https://cash.me/$AlexEpstein) ###### BTC: 38Q5VbH63MtouxHu8BuPNLzfY5B5RNVMDn ###### ETH: 0xf7c60C06D298FF954917eA45206426f79d40Ac9D ###### LTC: LWZ3T19YUk66dgkczN7dRhiXDMqSYrXUV4 #### Inspired by: [Ruby-Scripts](https://github.com/jakewmeyer/Ruby-Scripts) ## License MIT License Copyright (c) 2017 Alex Epstein Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: bak2dvd/bak2dvd ================================================ #!/usr/bin/env bash # Author: Charles Oblender https://github.com/oblende currentVersion="1.23.0" configuredClient="" tarwrite() { tl=$1 pn=$2 tops=$3 # FreeBSD needs to use gtar # Make this a function for the addition of a restore option # These if statements test for all possible combinations of null strings and executes the permutation # of tar or gtar that excludes the null string. if command -v gtar &>/dev/null then if [[ -z "$tops" && -n "$dir" && -n "$excludes" ]] then gtar -cvpML "$tl" -f "$pn" "${dir[@]}" "${excludes[@]}" "${filenames[@]}" <&7 & tarpid=$! countlimit=2 return elif [[ -n "$tops" && -z "$dir" && -n "$excludes" ]] then gtar -cvpML "$tl" -f "$pn" "$tops" "${excludes[@]}" "${filenames[@]}" <&7 & tarpid=$! countlimit=2 return elif [[ -n "$tops" && -n "$dir" && -z "$excludes" ]] then gtar -cvpML "$tl" -f "$pn" "$tops" "${dir[@]}" "${filenames[@]}" <&7 & tarpid=$! countlimit=2 return elif [[ -n "$tops" && -z "$dir" && -n "$excludes" ]] then gtar -cvpML "$tl" -f "$pn" "$tops" "${excludes[@]}" "${filenames[@]}" <&7 & tarpid=$! countlimit=2 return elif [[ -n "$tops" && -z "$dir" && -z "$excludes" ]] then gtar -cvpML "$tl" -f "$pn" "$tops" "${filenames[@]}" <&7 & tarpid=$! countlimit=2 return elif [[ -z "$tops" && -z "$dir" && -n "$excludes" ]] then gtar -cvpML "$tl" -f "$pn" "${excludes[@]}" "${filenames[@]}" <&7 & tarpid=$! countlimit=2 return elif [[ -z "$tops" && -z "$dir" && -z "$excludes" ]] then gtar -cvpML "$tl" -f "$pn" "${filenames[@]}" <&7 & tarpid=$! countlimit=2 return else gtar -cvpML "$tl" -f "$pn" "$tops" "${dir[@]}" "${excludes[@]}" "${filenames[@]}" <&7 & tarpid=$! countlimit=2 return fi fi if command -v tar &>/dev/null then if [[ -z "$tops" && -n "$dir" && -n "$excludes" ]] then tar -cvpML "$tl" -f "$pn" "${dir[@]}" "${excludes[@]}" "${filenames[@]}" <&7 & tarpid=$! countlimit=1 return elif [[ -n "$tops" && -z "$dir" && -n "$excludes" ]] then tar -cvpML "$tl" -f "$pn" "$tops" "${excludes[@]}" "${filenames[@]}" <&7 & tarpid=$! countlimit=1 return elif [[ -n "$tops" && -n "$dir" && -z "$excludes" ]] then tar -cvpML "$tl" -f "$pn" "$tops" "${dir[@]}" "${filenames[@]}" <&7 & tarpid=$! countlimit=1 return elif [[ -n "$tops" && -z "$dir" && -n "$excludes" ]] then tar -cvpML "$tl" -f "$pn" "$tops" "${excludes[@]}" "${filenames[@]}" <&7 & tarpid=$! countlimit=1 return elif [[ -n "$tops" && -z "$dir" && -z "$excludes" ]] then tar -cvpML "$tl" -f "$pn" "$tops" "${filenames[@]}" <&7 & tarpid=$! countlimit=1 return elif [[ -z "$tops" && -z "$dir" && -n "$excludes" ]] then tar -cvpML "$tl" -f "$pn" "${excludes[@]}" "${filenames[@]}" <&7 & tarpid=$! countlimit=1 return elif [[ -z "$tops" && -z "$dir" && -z "$excludes" ]] then tar -cvpML "$tl" -f "$pn" "${filenames[@]}" <&7 & tarpid=$! countlimit=1 return else tar -cvpML "$tl" -f "$pn" "$tops" "${dir[@]}" "${excludes[@]}" "${filenames[@]}" <&7 & tarpid=$! countlimit=1 fi fi } tarread() { pn=$1 tops=$2 # These if statements test for null strings and then excutes the permutation of tar or gtar # that excludes the null strings. if command -v gtar &>/dev/null then if [[ -n "$tops" && -n "$dir" && -z "$filenames" ]] then gtar -xvpMf "$pn" "$tops" "${dir[@]}" <&7 & tarpid=$! countlimit=2 return elif [[ -n "$tops" && -z "$dir" && -n "$filenames" ]] then gtar -xvpMf "$pn" "$tops" "${filenames[@]}" <&7 & tarpid=$! countlimit=2 return elif [[ -n "$tops" && -z "$dir" && -z "$filenames" ]] then gtar -xvpMf "$pn" "$tops" <&7 & tarpid=$! countlimit=2 return elif [[ -z "$tops" && -n "$dir" && -n "$filenames" ]] then gtar -xvpMf "$pn" "${dir[@]}" "${filenames[@]}" <&7 & tarpid=$! countlimit=2 return elif [[ -z "$tops" && -n "$dir" && -z "$filenames" ]] then gtar -xvpMf "$pn" "${dir[@]}" <&7 & tarpid=$! countlimit=2 return elif [[ -z "$tops" && -z "$dir" && -n "$filenames" ]] then gtar -xvpMf "$pn" "${filenames[@]}" <&7 & tarpid=$! countlimit=2 return elif [[ -z "$tops" && -z "$dir" && -z "$filenames" ]] then gtar -xvpMf "$pn" <&7 & tarpid=$! countlimit=2 return else gtar -xvpMf "$pn" "$tops" "${dir[@]}" "${filenames[@]}" <&7 & tarpid=$! countlimit=2 return fi fi if command -v tar &>/dev/null then if [[ -n "$tops" && -n "$dir" && -z "$filenames" ]] then tar -xvpMf "$pn" "$tops" "${dir[@]}" <&7 & tarpid=$! countlimit=1 return elif [[ -n "$tops" && -z "$dir" && -n "$filenames" ]] then tar -xvpMf "$pn" "$tops" "${filenames[@]}" <&7 & tarpid=$! countlimit=1 return elif [[ -n "$tops" && -z "$dir" && -z "$filenames" ]] then tar -xvpMf "$pn" "$tops" <&7 & tarpid=$! countlimit=1 return elif [[ -z "$tops" && -n "$dir" && -n "$filenames" ]] then tar -xvpMf "$pn" "${dir[@]}" "${filenames[@]}" <&7 & tarpid=$! countlimit=1 return elif [[ -z "$tops" && -n "$dir" && -z "$filenames" ]] then tar -xvpMf "$pn" "${dir[@]}" <&7 & tarpid=$! countlimit=1 return elif [[ -z "$tops" && -z "$dir" && -n "$filenames" ]] then tar -xvpMf "$pn" "${filenames[@]}" <&7 & tarpid=$! countlimit=1 return elif [[ -z "$tops" && -z "$dir" && -z "$filenames" ]] then tar -xvpMf "$pn" <&7 & tarpid=$! countlimit=1 return else tar -xvpMf "$pn" "$tops" "${dir[@]}" "{$filenames[@]}" <&7 & tarpid=$! countlimit=1 fi fi } discread() { dev=$1 pn=$2 tpid=$3 counter=$4 countlim=$5 rl=$6 # FreeBSD is a brain damaged OS written by brain damaged developers who, when given a choice, will run headlong into # making a task or operation as difficult as possible. if [[ $(uname | grep "FreeBSD" | wc -l) -gt 0 ]] then while [ "$counter" -eq "$countlim" ] do dd if="$dev" of="$pn" bs=2048 eject "$dev" counter=0 counter=$(ps -A | grep $tarpid | wc -l) if [[ $counter -eq $countlim ]] then echo read -p "Insert next disc and press Enter:" response echo "$response" >&7 fi done else while [ "$counter" -eq "$countlim" ] do dd if="$dev" of="$pn" bs=1k count="$rl" eject "$dev" counter=0 counter=$(ps -A | grep $tarpid | wc -l) if [[ $counter -eq $countlim ]] then read -p "Insert next disc and press Enter:" response echo "$response" >&7 fi done fi } dvdburn() { counter=$4 countlim=$5 altburn=$6 while [ "$counter" -eq "$countlim" ] do if [[ $(echo "$1" | grep "dev" | wc -l) -eq 0 ]] then echo "DVD or BluRay burning requires device from /dev." exitcode=1 cleanup $exitcode fi # Growisofs is untrustworthy for DL media, and is slow for BD-RE/DVD-RAM media because of defect management. case "$altburn" in cdrskin) # cdrskin doesn't like -multi when burning BD-R media. # BD-RE media needs to be formatted before recording cdrskin dev="$1" blank=as_needed stream_recording=on driveropts=burnfree -tao -eject -data "$2" ;; xorrecord) xorrecord dev="$1" blank=as_needed stream_recording=on driveropts=burnfree -tao -multi -eject -data "$2" ;; *) growisofs -Z "$1"="$2" esac counter=0 counter=$(ps -A | grep "$3" | wc -l) if [[ $counter -eq $countlim ]] then read -p "Insert next disc and press Enter:" response echo "$response" >&7 fi done # dvd-r restore needs tracklen + 4. Need to check +r single and dual layer as well as bd medias. Joy. # DVD+R needs no compensation. } cdburn() { counter=$4 countlim=$5 cdb=$6 while [ "$counter" -eq "$countlim" ] do if [[ $(uname | grep "FreeBSD" | wc -l) -gt 0 ]] then if [[ $(echo "$1" | grep "dev" | wc -l) -gt 0 && $(echo "$cdb" | grep "cdrecord" | wc -l) -gt 0 ]] then echo "CD burning requires SCSI address in the form of b,t,l. Please use cdrecord -scanbus for a list of possible SCSI addresses." exitcode=1 cleanup $exitcode fi elif [[ $(uname | grep "Linux" | wc -l) -gt 0 ]] then if [[ $(echo "$1" | grep "dev" | wc -l) -eq 0 ]] then # Chances are if it's Linux then wodim is being used and requires /dev/srX instead of SCSI address echo "CD burning in Linux with cdrecord or wodim requires device from /dev." exitcode=1 cleanup $exitcode fi fi case "$cdb" in cdrecord) cdrecord dev="$1" driveropts=burnfree -tao -multi -eject -data "$2" #Turned burnfree on just in case. Restore needs tracklen + 8 ;; wodim) wodim dev="$1" driveropts=burnfree -tao -multi -eject -data "$2" ;; cdrskin) cdrskin dev="$1" driveropts=burnfree -tao -multi -eject -data "$2" ;; xorrecord) xorrecord dev="$1" driveropts=burnfree -tao -multi -eject -data "$2" ;; esac counter=0 counter=$(ps -A | grep "$3" | wc -l) if [[ $counter -eq $countlim ]] then read -p "Insert next disc and press Enter:" response echo "$response" >&7 fi done } cleanup() { kill $tarpid &>/dev/null rm "$pipename" rm "$fifoname" exit "$1" } getCDburner() { if command -v cdrecord &>/dev/null then cdburner="cdrecord" return fi if command -v wodim &>/dev/null then cdburner="wodim" return fi if command -v cdrskin &>/dev/null then cdburner="cdrskin" return fi if command -v xorrecord &>/dev/null then cdburner="xorrecord" return fi } # This function finds an alternative burner to growisofs if DVD-DL, DVD-RAM, or BD-R(E) media is chosen to improve speed # or to actually write a full dataset in the case of DVD-DL media. getAltDVDburner() { if command -v cdrskin &>/dev/null then altdvdburner="cdrskin" return fi if command -v xorrecord &>/dev/null then altdvdburner="xorrecord" return else echo "To burn DVD-DL or BD media xorriso or cdrskin needs to be installed." echo "I can burn using growisofs, but it may not burn DVD-DL media correctly or will burn BD-RE media very slowly." read -p "If you wish to continue using growisofs then type YES then press [Enter], else just press [Enter] to abort: " yesno if [[ "$yesno" -eq "YES" ]] then if command -v growisofs &>/dev/null then altdvdburner="growisofs" fi else exitcode=1 cleanup $exitcode fi fi } ## This function determines which http get tool the system has installed and returns an error if there isnt one getConfiguredClient() { if command -v curl &>/dev/null; then configuredClient="curl" elif command -v wget &>/dev/null; then configuredClient="wget" elif command -v http &>/dev/null; then configuredClient="httpie" elif command -v fetch &>/dev/null; then configuredClient="fetch" else echo "Error: This tool requires either curl, wget, httpie or fetch to be installed." >&2 return 1 fi } ## Allows to call the users configured client without if statements everywhere httpGet() { case "$configuredClient" in curl) curl -A curl -s "$@" ;; wget) wget -qO- "$@" ;; httpie) http -b GET "$@" ;; fetch) fetch -q "$@" ;; esac } update() { # Author: Alexander Epstein https://github.com/alexanderepstein # Update utility version 1.2.0 # To test the tool enter in the defualt values that are in the examples for each variable repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then echo "Error: update utility has not been configured correctly." >&2 exit 1 elif [[ $latestVersion == "" ]]; then echo "Error: no active internet connection" >&2 exit 1 else if [[ "$latestVersion" != "$currentVersion" ]]; then echo "Version $latestVersion available" echo -n "Do you wish to update $repositoryName [Y/n]: " read -r answer if [[ "$answer" == [Yy] ]]; then cd ~ || { echo 'Update Failed'; exit 1; } if [[ -d ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi git clone "https://github.com/$githubUserName/$repositoryName" || { echo "Couldn't download latest version"; exit 1; } cd $repositoryName || { echo 'Update Failed'; exit 1; } git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit." chmod a+x install.sh #this might be necessary in your case but wasnt in mine. ./$nameOfInstallFile "update" || exit 1 cd .. rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; } else exit 1 fi else echo "$repositoryName is already the latest version" fi fi } checkInternet() { httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request } usage() { cat <&2 exit 1 ;; -h|--help) usage exit 0 ;; -v) echo "Version $currentVersion" exit 0 ;; -u|update) getConfiguredClient || exit 1 checkInternet || exit 1 update exit 0 ;; -d) shift if test $# -gt 0; then device=$1 else echo "No optical device specified" >&2 exit 1 fi shift options=1 ;; -dvd) tracklen=4580000 # DVD+R capacity - 10M comp=0 shift options=1 ;; -dvd-ram) # DVD-RAM for those who have this under appreciated, and under utilized media format tracklen=4463168 # DVD-RAM capacity - 10M comp=2 shift getAltDVDburner # Media has same defect management as BD-RE. In fact you might call it the orginal. options=1 ;; -dvd-dl) tracklen=8337408 # DVD+R DL capacity - 10M comp=2 shift getAltDVDburner options=1 ;; -dvd-r) tracklen=4585536 #DVD-R single layer capacity -10M comp=4 shift options=1 ;; -bd) tracklen=24166400 # This should be 10M less than total. Had miscalculated, now correct. comp=0 shift getAltDVDburner # While growisofs canb be trusted, it'll be slow with *any* bd-re media because of defect management. options=1 ;; -bd-dl) tracklen=47294464 #same as above but dual layer comp=6 shift getAltDVDburner options=1 ;; -cd) tracklen=712702 #700M cd-rom capacity - 4k, 10M is not an insigficant amount at this storage capacity! comp=8 shift getCDburner options=1 ;; -a) shift if test $# -gt 0; then filenames=( "${filenames[@]}" "$1" ) else echo "No filename or directory specified" >&2 exit 1 fi shift ;; -C) shift if test $# -gt 0; then dir=( "-C" ) dir=( "${dir[@]}" "$1" ) else echo "No directory specified." >&2 exit 1 fi shift ;; -t) shift if test $# -gt 0; then taropts=$1 else echo "No options to tar specified." >&2 exit 1 fi shift options=1 ;; -r) rw=2 shift ;; -w) rw=1 shift ;; -X) shift if test $# -gt 0; then excludes=( "${excludes[@]}" "--exclude=" ) excludes=( "${excludes[@]}""$1" ) else echo "No excluded file or directory specified." exit 1 fi shift ;; :) echo "Option -$1 requires an argument." >&2 exit 1 ;; *) echo "Something bad happened or malformed arguments." exit 1 ;; esac done # special set of first arguments that have a specific behavior across tools if [[ $# == "0" && $options == "0" ]]; then usage ## if calling the tool with no flags and args chances are you want to return usage exit 0 elif [[ $# == "1" ]]; then if [[ $1 == "update" ]]; then getConfiguredClient || exit 1 checkInternet || exit 1 update || exit 1 exit 0 elif [[ $1 == "help" ]]; then usage exit 0 fi fi ## The rest of the conditions and code would go here ## Make sure to use checkInternet at least once before any time httpGet will be called. ## Make sure to call getConfiguredClient at least once before ever calling checkInternet. trap "cleanup 2" 2 pipename="/tmp/$RANDOM.pipe" fifoname="/tmp/$RANDOM.fifo" #changed from mknod to mkfifo to make script more cross platform mkfifo $pipename mkfifo $fifoname tarpid="" # Asign the fifo to a file descriptor. No need for ugly cat hack, and it actually works! exec 7<>$fifoname declare -i readlen countlimit="" # If no -d option was set then the script will be able to get this far, but will be stopped # otherwise confusing errors will happen. May change to give the user a chance to specify a device or quit at this point. if [[ -z "$device" ]] then echo "No device specified." exitcode=1 cleanup $exitcode fi if [[ $rw -eq 1 ]] then tarwrite $tracklen $pipename "$taropts" elif [[ $rw -eq 2 ]] then readlen=$tracklen+$comp tarread $pipename "$taropts" fi count=$(ps -A | grep "$tarpid" | wc -l) # Check that tar is alive and prompt for media if [[ $count -eq $countlimit ]] then read -p "Insert media and press Enter:" if [[ $rw -eq 1 ]] then #call appropriate burning function here. Want to add support for mini CD's and mini DVD's at some point. if [[ $tracklen -le 712702 ]] then cdburn "$device" $pipename "$tarpid" "$count" "$countlimit" "$cdburner" else dvdburn "$device" $pipename "$tarpid" "$count" "$countlimit" "$altdvdburner" fi elif [[ $rw -eq 2 ]] then discread "$device" $pipename "$tarpid" "$count" "$countlimit" $readlen else echo "You need to specify option -w for writing a backup or -r for restoring from backup." exitcode=1 cleanup $exitcode fi else # otherwise something has gone wrong and we need to stop echo echo "Tar has died unexpectedly." >&2 # Call cleanup function here exitcode=1 cleanup $exitcode fi exitcode=0 cleanup $exitcode # This exit is a sheet anchor. It probably isn't needed, but it makes me feel better. exit 0 ================================================ FILE: bash-snippets/bash-snippets ================================================ #!/usr/bin/env bash # Author: Navan Chauhan and Alexander Epstein declare -a tools=(bak2dvd cheat cloudup crypt cryptocurrency currency geo lyrics meme movies newton pwned qrify short siteciphers stocks taste todo transfer weather ytview) declare -a validTools=() currentVersion="1.23.0" configuredClient="" ## This function determines which http get tool the system has installed and returns an error if there isnt one getConfiguredClient() { if command -v curl &>/dev/null; then configuredClient="curl" elif command -v wget &>/dev/null; then configuredClient="wget" elif command -v http &>/dev/null; then configuredClient="httpie" elif command -v fetch &>/dev/null; then configuredClient="fetch" else echo "Error: This tool requires either curl, wget, httpie or fetch to be installed." >&2 return 1 fi } httpGet() { case "$configuredClient" in curl) curl -A curl -s "$@" ;; wget) wget -qO- "$@" ;; httpie) http -b GET "$@" ;; fetch) fetch -q "$@" ;; esac } grablatestversion() { repositoryName="Bash-Snippets" githubUserName="alexanderepstein" latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option } checkInternet() { httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request } header() { title="Bash Snippets" installver="Installed Version: $currentVersion" latestver="Latest Version: $latestVersion" printf "\t\t\t\t %s\n" "$title" printf "\t\t%s\t\t%s\n" "$latestver" "$installver" } toolMenu() { while true; do clear header count=1 for command in "${validTools[@]}"; do if [[ $count -gt 9 ]];then c=$count else c="0$count"; fi spaces=$((40 - $(echo "$command" | wc -c))) echo -n -e "\t\t\t$c." for (( i = 0 ; i < $spaces; i++)) ;do printf " " done echo "$command" count=$(( $count + 1 )) done echo -e -n "\t\tChoose a tool or just press enter to go back: " read choice if [[ $choice == "" ]];then clear; header; break; fi echo -e -n "\t\tEnter any arguments you want to use with the tool: " read args clear if [[ $choice =~ [0-9] ]]; then ${validTools[$(($choice-1))]} "$args" else $choice "$args"; fi exit 0 done } menu() { while true; do echo -e "\t\t\t01.\t\t\t\tTools" echo -e "\t\t\t02.\t\t\t\tInstallation Check" echo -e "\t\t\t03.\t\t\t\tView man page" echo -e "\t\t\t04.\t\t\t\tUpdate" echo -e "\t\t\t05.\t\t\t\tDonate" echo -e "\t\t\t06.\t\t\t\tQuit" echo -e -n "\n\t\t\tChoose an option: " read choice if [[ $choice -gt 6 || $choice -lt 1 ]];then echo "Error invalid option!" sleep 2 clear header continue fi clear header if [[ $choice -eq 1 ]];then toolMenu elif [[ $choice -eq 2 ]];then installationcheck elif [[ $choice -eq 3 ]];then man bash-snippets elif [[ $choice -eq 4 ]];then ${validTools[1]} -u sleep 2 clear header elif [[ $choice -eq 5 ]];then clear echo -e "\t\tThanks for thinking of donating, that's pretty cool of you" echo -e "\n\t\tCryptocurrency Donation Addresses" echo -e "\t\t\tBTC: 38Q5VbH63MtouxHu8BuPNLzfY5B5RNVMDn" echo -e "\t\t\tETH: 0xf7c60C06D298FF954917eA45206426f79d40Ac9D" echo -e "\t\t\tLTC: LWZ3T19YUk66dgkczN7dRhiXDMqSYrXUV4\n" echo -e "\t\tNormal Methods" echo -e "\t\t\tVenmo: AlexanderEpstein" echo -e "\t\t\tSquare Cash: AlexEpstein\n\n\n\n" exit 0 elif [[ $choice -eq 6 ]]; then clear; exit 0 fi done } installationcheck() { validTools=() for tool in "${tools[@]}"; do if [ -e "/usr/local/bin/$tool" ]; then state="present"; start=51; validTools+=($tool); else state="absent"; start=52; fi if $1; then echo -n -e "\t\t$tool" spaces=$(($start - $( echo "$tool" | wc -c))) for (( i = 0 ; i < $spaces; i++)) ;do printf " " done echo $state fi done if $1; then echo -n "Press enter to go back to the menu" read clear header fi } if [[ $# -eq 0 ]]; then clear checkInternet getConfiguredClient grablatestversion header installationcheck false echo menu elif [[ $# -eq 1 ]]; then if [[ $1 == "-u" || $1 == "update" ]]; then installationcheck false ${validTools[1]} -u elif [[ $1 == "-h" || $1 == "help" ]]; then man bash-snippets elif [[ $1 == "-v" ]]; then echo "Version $currentVersion" fi fi ================================================ FILE: bash-snippets.1 ================================================ .\" generated with Ronn/v0.7.3 .\" http://github.com/rtomayko/ronn/tree/0.7.3 . .TH "BASH\-SNIPPETS" "1" "April 2020" "" "" . .SH "NAME" \fBbash\-snippets\fR \- A collection of small bash scripts for heavy terminal users . .SH "Tools" . .SS "Cheat" Description: Cheatsheets for quick information about multiple programming languages along with terminal commands . .P Usage: cheat [flags] [command] or cheat [flags] [programming language] [subject] . .IP "\(bu" 4 \-s Does a search for last argument rather than looking for exact match . .IP "\(bu" 4 \-i Case insensitive search . .IP "\(bu" 4 \-b Word boundaries in search . .IP "\(bu" 4 \-r Recursive search . .IP "\(bu" 4 \-u Update Bash\-Snippet Tools . .IP "\(bu" 4 \-h Show the help . .IP "\(bu" 4 \-v Get the tool version . .IP "" 0 . .P Special Pages: . .IP "\(bu" 4 hello Describes building the hello world program written in the language . .IP "\(bu" 4 list This lists all cheatsheets related to previous arg if none it lists all cheatsheets . .IP "\(bu" 4 learn Shows a learn\-x\-in\-minutes language cheat sheet perfect for getting started with the language . .IP "\(bu" 4 1line A collection of one\-liners in this language . .IP "\(bu" 4 weirdness A collection of examples of weird things in this language . .IP "" 0 . .P Examples: . .IP "\(bu" 4 cheat rust hello . .IP "\(bu" 4 cheat \-r \-b \-i go . .IP "\(bu" 4 cheat julia Functions . .IP "\(bu" 4 cheat \-i go operators . .IP "" 0 . .SS "Cloudup" Description: Backs up a users github repositories to your bitbucket account\. With no flags cloudup will guide you through backing up a single repository . .P Usage: cloudup [flags] or cloudup [flags] [listOfGHRepoNamesSplitBySpaces] . .IP "\(bu" 4 \-p Upload the repositor(y)(ies) as private to bitbucket (must have private repo ability on bitbucket) . .IP "\(bu" 4 \-a Backup all github repositories . .IP "\(bu" 4 \-s Only backup repositories that you have created (no forks) (only works in conjunction with the \-a flag) . .IP "\(bu" 4 \-t Backup the repository with a timestamp added to the repostiory name (will always create a new unique bitbucket repo) . .IP "\(bu" 4 \-u Update Bash\-Snippet Tools . .IP "\(bu" 4 \-h Show the help . .IP "\(bu" 4 \-v Get the tool version . .IP "" 0 . .P Examples: . .IP "\(bu" 4 cloudup . .IP "\(bu" 4 cloudup \-p \-a . .IP "\(bu" 4 cloudup \-p nameOfRepo1 nameOf Repo2 . .IP "\(bu" 4 cloudup nameOfRep . .IP "" 0 . .SS "Crypt" Description: A wrapper around openssl that facilitates encrypting and decrypting files\. . .P Usage: crypt [flag] [inputFile] [outputFile] . .IP "\(bu" 4 \-e Encrypt the inputFile and store it in the outputFil . .IP "\(bu" 4 \-d Decrypt the inputFile and store it in the outputFil . .IP "\(bu" 4 \-u Update Bash\-Snippet Tools . .IP "\(bu" 4 \-h Show the help . .IP "\(bu" 4 \-v Get the tool version . .IP "" 0 . .P Examples: . .IP "\(bu" 4 crypt \-e mySecretFile\.txt myEncryptedFile\.jpg (change filetype so default program is incorrect) . .IP "\(bu" 4 crypt \-d myEncryptedFile\.jpg thisIsNowDecrypted\.txt (change filetype back so now default program is correct) . .IP "" 0 . .SS "CryptoCurrency" Description: A realtime cryptocurrency converter\. With no flags it will pull down the latest stats of the top 10 cryptos . .P Usage: cryptocurrency or cryptocurrency [flag] or cryptocurrency [flag] [arg] . .IP "\(bu" 4 \-o Utilize the old functionality of the tool . .IP "\(bu" 4 \-f Fiat currency for conversions . .IP "\(bu" 4 \-u Update Bash\-Snippet Tools . .IP "\(bu" 4 \-h Show the help . .IP "\(bu" 4 \-v Get the tool version . .IP "" 0 . .P Examples: cryptocurrency \-o cryptocurrency \-f eur . .SS "Currency" Description: A realtime currency converter\. With no flags it will guide you through the currency exchange . .P Usage: currency or currency [flag] or currency [base] [exchangeTo] [amount] . .IP "\(bu" 4 \-u Update Bash\-Snippet Tools . .IP "\(bu" 4 \-h Show the help . .IP "\(bu" 4 \-v Get the tool version . .IP "" 0 . .P Supported Currencies: . .P | AUD | BGN | BRL | CAD | | CHF | CNY | CZK | DKK | | EUR | GBP | HKD | HRK | | HUF | IDR | ILS | INR | | JPY | KRW | MXN | MYR | | NOK | NZD | PHP | PLN | | RON | RUB | SEK | SGD | | THB | TRY | USD | ZAR | . .P Examples: . .IP "\(bu" 4 currency EUR USD 12\.35 . .IP "\(bu" 4 currency . .IP "" 0 . .SS "Geo" Description: Provides quick access for wan, lan, router, dns, mac, and ip geolocation data . .P Usage: geo [flag] . .IP "\(bu" 4 \-w Returns WAN IP . .IP "\(bu" 4 \-l Returns LAN IP(s) . .IP "\(bu" 4 \-r Returns Router IP . .IP "\(bu" 4 \-d Returns DNS Nameserver . .IP "\(bu" 4 \-m Returns MAC address for interface\. Ex\. eth0 . .IP "\(bu" 4 \-g Returns Current IP Geodata . .IP "" 0 . .P Examples: . .IP "\(bu" 4 geo \-g . .IP "\(bu" 4 geo \-wlrdgm eth0 . .IP "" 0 . .P Custom Geo Output => [all] [query] [city] [region] [country] [zip] [isp] . .P Example: geo \-a 8\.8\.8\.8 \-o city,zip,isp . .IP "\(bu" 4 \-o [options] Returns Specific Geodata . .IP "\(bu" 4 \-a [address] For specific ip in \-s . .IP "\(bu" 4 \-v Returns Version . .IP "\(bu" 4 \-h Returns Help Screen . .IP "\(bu" 4 \-u Updates Bash\-Snippets . .IP "" 0 . .SS "Gist" Description: Manage your gists with git and Github API v3 . .P Usage: gist [command] [args] . .IP "\(bu" 4 [star|all] List your gists, use \'star\' as argument for your starred gists, \'all\' or \'a\' for both your and starred gists\. Format for each line is: \fIINDEX\fR \fIURL\fR \fIFILE_NUM\fR \fICOMMENT_NUM\fR \fIDESCRIPTION\fR . .IP "\(bu" 4 fetch Update the local list of your gists, \'star\' as argument for your starred gists . .IP "\(bu" 4 \fIINDEX\fR Show the path of local gist repo and do custom actions . .IP "\(bu" 4 new Create a new gist with files or STDIN . .IP "\(bu" 4 grep Grep gists by description, filename and content with a given pattern . .IP "\(bu" 4 tag Modify/List tags for a gist . .IP "\(bu" 4 tags List all tags and pinned tags . .IP "\(bu" 4 pin, Pin/Unpin tags, or filter gists with pinned tags . .IP "\(bu" 4 lan Filter gists or list gist with coding languages . .IP "\(bu" 4 detail Show the detail of a gist . .IP "\(bu" 4 edit Edit description for a gist . .IP "\(bu" 4 delete Delete gists by given indices . .IP "\(bu" 4 push Push changes by git . .IP "\(bu" 4 clean Clean local repos of removed gists . .IP "\(bu" 4 config Do configuration . .IP "\(bu" 4 user Get list of gists with a given Github user . .IP "\(bu" 4 github Import selected gist as a new Github repo . .IP "\(bu" 4 help Show the helper message . .IP "" 0 . .P Example: . .IP "\(bu" 4 gist (Show your gists) . .IP "\(bu" 4 gist tag (Show your gists with tags) . .IP "\(bu" 4 gist fetch (update the list of gists from github\.com) . .IP "\(bu" 4 gist 3 (show the repo path of your 3rd gist, and do custom actions) . .IP "\(bu" 4 gist 3 \-\-no\-action (show the repo path of your 3rd gist, and do not perform actions) . .IP "\(bu" 4 gist new \-\-desc bar foo (create a new gist with files and description) . .IP "" 0 . .SS "Lyrics" Description: Fetch lyrics for a certain song\. . .P Usage: lyrics [flags] or tool [\-a] [arg] [\-s] [arg] . .IP "\(bu" 4 \-a Artist of the song to fetch lyrics for . .IP "\(bu" 4 \-s Song of the artist to fetch lyrics for . .IP "\(bu" 4 \-f Export the lyrics to file rather than outputting to stdout . .IP "\(bu" 4 \-u Update Bash\-Snippet Tools . .IP "\(bu" 4 \-h Show the help . .IP "\(bu" 4 \-v Get the tool version . .IP "" 0 . .P Examples: . .IP "\(bu" 4 lyrics \-a logic \-s run it . .IP "\(bu" 4 lyrics \-a logic \-s run it \-f ~/runItLyrics\.txt . .IP "" 0 . .SS "Meme" Description: A lightning fast meme generator . .P Usage: tool [flags] or tool [flags] [arguments] . .IP "\(bu" 4 \-u Update Bash\-Snippet Tools . .IP "\(bu" 4 \-h Show the help . .IP "\(bu" 4 \-f Choose the output filename . .IP "\(bu" 4 \-v Get the tool version . .IP "" 0 . .P Examples: . .IP "\(bu" 4 meme \-f dogeMeme . .IP "" 0 . .SS "Movies" Description: Provides relevant information about a certain movie\. . .P Usage: movies [flag] or movies [movieToSearch] . .IP "\(bu" 4 \-u Update Bash\-Snippet Tools . .IP "\(bu" 4 \-h Show the help . .IP "\(bu" 4 \-v Get the tool version . .IP "\(bu" 4 \-d Show detailed information . .IP "" 0 . .P Examples: . .IP "\(bu" 4 movies Argo . .IP "\(bu" 4 movies Inception . .IP "" 0 . .SS "Newton" Description: Performs numerical calculations all the way up to symbolic math parsing\. . .P Usage: newton [operation] [expression] or newton [flag] . .IP "\(bu" 4 \-u Update Bash\-Snippet Tools . .IP "\(bu" 4 \-h Show the help . .IP "\(bu" 4 \-v Get the tool version . .IP "" 0 . .P Valid Symbols: + add \- subtract [ left parenthesis (you must use brackets bash has a bultin for parenthesis) ] right parenthesis (you must use brackets bash has a bultin for parenthesis) * multiply / divide ^ power : between the range of left and right side (only for area under curve) ~ parameter on right side (only for area, tangent line and log) . .P Examples: . .IP "\(bu" 4 newton simplify [[2x]+7]*[4x] . .IP "\(bu" 4 movies derive x+2x . .IP "" 0 . .SS "Pwned" Usage: pwned [email] . .P Description: Checks where an email account has been breached . .IP "" 4 . .nf * \-u Update Bash\-Snippet Tools * \-h Show the help * \-v Get the tool version . .fi . .IP "" 0 . .P Examples: . .IP "" 4 . .nf * pwned emailtocheck@email\.com . .fi . .IP "" 0 . .SS "Qrify" Usage: qrify [stringtoturnintoqrcode] . .P Description: Converts strings or urls into a qr code\. . .IP "" 4 . .nf * \-u Update Bash\-Snippet Tools * \-m Enable multiline support * \-f Save the QRCode to a file * \-d Decode the QR code from a PNG/GIF/JP(E)G file * \-h Show the help * \-v Get the tool version . .fi . .IP "" 0 . .P Examples: . .IP "" 4 . .nf * qrify this is a test string * qrify \-m two \en lines * qrify \-f fileNameHere Insert what you want to encode here * qrify github\.com # notice no http:// or https:// this will fail * qrify \-d fileName\.png . .fi . .IP "" 0 . .SS "Short" Description: Unmasks shortended urls\. . .P Usage: short [shortURL] or short [flag] . .IP "\(bu" 4 \-e Expand the following URL . .IP "\(bu" 4 \-s Shorten the following URL . .IP "\(bu" 4 \-u Update Bash\-Snippet Tools . .IP "\(bu" 4 \-h Show the help . .IP "\(bu" 4 \-v Get the tool version . .IP "" 0 . .P Example: . .IP "\(bu" 4 Input: short \-e tinyurl\.com/jhkj . .IP "\(bu" 4 Output: http://possiblemaliciouswebsiteornot\.com . .IP "\(bu" 4 Input: short \-s google\.com . .IP "\(bu" 4 Output: http://ki\.tc/23sd1d . .IP "" 0 . .SS "Siteciphers" Description: Checks the available ciphers for the SSL of an https site\. . .P Usage: siteciphers [flag] or siteciphers [optionalDFlag] [website] . .IP "\(bu" 4 \-u Update Bash\-Snippet Tools . .IP "\(bu" 4 \-h Show the help . .IP "\(bu" 4 \-v Get the tool version . .IP "\(bu" 4 \-d Set the delay between requests sent to the site (default is 1 sec) . .IP "" 0 . .P Examples: . .IP "\(bu" 4 siteciphers github\.com . .IP "\(bu" 4 siteciphers \-d 0\.75 google\.com . .IP "" 0 . .SS "Stocks" Description: Finds the latest information on a certain stock\. . .P Usage: stocks [flag] or stocks [company/ticker] . .IP "\(bu" 4 \-u Update Bash\-Snippet Tools . .IP "\(bu" 4 \-h Show the help . .IP "\(bu" 4 \-v Get the tool version . .IP "" 0 . .P Examples: . .IP "\(bu" 4 stocks AAPL . .IP "\(bu" 4 stocks Tesla . .IP "" 0 . .SS "Taste" Description: A recommendation engine that provides 3 similar items based on some input topic\. Taste also has the ability to provide information on the item of interest\. Supports: shows, books, music, artists, movies, authors, games . .P Usage: taste [flag] [item] . .IP "\(bu" 4 \-i Get more information on similar items . .IP "\(bu" 4 \-s Get information on the item itself . .IP "\(bu" 4 \-u Update Bash\-Snippet Tools . .IP "\(bu" 4 \-h Show the help . .IP "\(bu" 4 \-v Get the tool version . .IP "" 0 . .P Examples: . .IP "\(bu" 4 taste \-i Kendrick Lamar . .IP "\(bu" 4 taste Catcher in the Ry . .IP "\(bu" 4 taste \-s Red Hot Chili Peppers . .IP "" 0 . .SS "Todo" Description: A simplistic commandline todo list\. . .P Usage: todo [flags] or todo [flags] [arguments] . .IP "\(bu" 4 \-c Clear all the current tasks . .IP "\(bu" 4 \-r Remove the following task number . .IP "\(bu" 4 \-g Get the current tasks . .IP "\(bu" 4 \-a Add the following task . .IP "\(bu" 4 \-u Update Bash\-Snippet Tools . .IP "\(bu" 4 \-h Show the help . .IP "\(bu" 4 \-v Get the tool version . .IP "" 0 . .P Examples: . .IP "\(bu" 4 todo \-a My very first task . .IP "\(bu" 4 todo \-r 1 . .IP "\(bu" 4 todo \-g . .IP "\(bu" 4 todo \-c . .IP "" 0 . .SS "Transfer" Description: Quickly transfer files from the command line\. . .P Usage: transfer [flags] or transfer [flag] [args] or transfer [filePathToUpload] . .IP "\(bu" 4 \-d Download a single file . .IP "" 4 . .nf * First arg: Output file directory * Second arg: File url id * Third arg: File name . .fi . .IP "" 0 . .IP "\(bu" 4 \-o Onetime file upload . .IP "\(bu" 4 \-u Update Bash\-Snippet Tools . .IP "\(bu" 4 \-h Show the help . .IP "\(bu" 4 \-v Get the tool version . .IP "" 0 . .P Examples: . .IP "\(bu" 4 transfer ~/fileToTransfer\.txt . .IP "\(bu" 4 transfer ~/firstFileToTransfer\.txt ~/secondFileToTransfer\.txt # upload multiple files at once . .IP "\(bu" 4 transfer \-d ~/outputDirectory fileID fileName . .IP "\(bu" 4 transfer \-o ~/fileToTransfer\.txt . .IP "" 0 . .SS "Weather" Description: Provides a 3 day forecast on your current location or a specified location\. With no flags Weather will default to your current location\. . .P Usage: weather or weather [flag] or weather [country] or weather [city] [state] . .IP "\(bu" 4 weather [optionalLocation] [i][M] get weather in imperial units, optional M means windspeed in m/s . .IP "\(bu" 4 weather [optionalLocation] [m][M] lowercase m gets weather in metric units, optional M means windspeed in m/s . .IP "\(bu" 4 weather [Moon] grabs the phase of the moon . .IP "\(bu" 4 \-u Update Bash\-Snippet Tools . .IP "\(bu" 4 \-h Show the help . .IP "\(bu" 4 \-v Get the tool version . .IP "" 0 . .P Examples: . .IP "\(bu" 4 weather . .IP "\(bu" 4 weather Paris m . .IP "\(bu" 4 weather Tokyo . .IP "\(bu" 4 weather Moon . .IP "\(bu" 4 weather mM . .IP "" 0 . .SS "Ytview" Description: Search and play youtube videos right from the terminal\. . .P Usage: ytview [flag] [string] or ytview [videoToSearch] . .IP "\(bu" 4 \-s Searches youtube . .IP "\(bu" 4 \-c Shows the latest videos of a channel . .IP "\(bu" 4 \-u Update Bash\-Snippet Tools . .IP "\(bu" 4 \-h Show the help . .IP "\(bu" 4 \-v Get the tool version . .IP "" 0 . .P Examples: . .IP "\(bu" 4 ytview \-s Family Guy Chicken Fight . .IP "\(bu" 4 ytview \-c Numberphile . .IP "" 0 . .SH "Updating" With any of the installed tools you can automate the update by running it with the \-u option or passing in update as the arguments . .IP "\(bu" 4 stocks update . .IP "" 0 . .P or . .IP "\(bu" 4 stocks \-u . .IP "" 0 . .P This will clone the repository and install the new versions of scripts that were installed, if you didn\'t install a certain tool this script will not install the new version of that tool\. . .SH "Uninstalling" If you don\'t have the Bash\-Snippets folder anymore clone the repository: git clone https://github\.com/alexanderepstein/Bash\-Snippets` . .P cd into the Bash\-Snippets directory: \fBcd Bash\-Snippets\fR . .IP "" 4 . .nf To go through a guided uninstall . .fi . .IP "" 0 . .IP "\(bu" 4 \&\./uninstall\.sh . .IP "" 0 . .SH "AUTHOR" Alexander Epstein Github: https://github\.com/alexanderepstein . .SH "Contributors" Jake Meyer Github: https://github\.com/jakewmeyer . .P Linyos Torovoltos Github: https://gitbub\.com/linyostorovovoltos . .SH "License" MIT License . .P Copyright (c) 2017 Alex Epstein . .P Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: . .P The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software\. . .P THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT\. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE\. ================================================ FILE: bash-snippets.1.html ================================================ bash-snippets(1) - A collection of small bash scripts for heavy terminal users
  1. bash-snippets(1)
  2. bash-snippets(1)

NAME

bash-snippets - A collection of small bash scripts for heavy terminal users

Tools

Cheat

Description: Cheatsheets for quick information about multiple programming languages along with terminal commands

Usage: cheat [flags] [command] or cheat [flags] [programming language] [subject]

Special Pages:

Examples:

Cloudup

Description: Backs up a users github repositories to your bitbucket account. With no flags cloudup will guide you through backing up a single repository

Usage: cloudup [flags] or cloudup [flags] [listOfGHRepoNamesSplitBySpaces]

Examples:

Crypt

Description: A wrapper around openssl that facilitates encrypting and decrypting files.

Usage: crypt [flag] [inputFile] [outputFile]

Examples:

CryptoCurrency

Description: A realtime cryptocurrency converter. With no flags it will pull down the latest stats of the top 10 cryptos

Usage: cryptocurrency or cryptocurrency [flag] or cryptocurrency [flag] [arg]

Examples: cryptocurrency -o cryptocurrency -f eur

Currency

Description: A realtime currency converter. With no flags it will guide you through the currency exchange

Usage: currency or currency [flag] or currency [base] [exchangeTo] [amount]

Supported Currencies:


| AUD | BGN | BRL | CAD | | CHF | CNY | CZK | DKK | | EUR | GBP | HKD | HRK | | HUF | IDR | ILS | INR | | JPY | KRW | MXN | MYR | | NOK | NZD | PHP | PLN | | RON | RUB | SEK | SGD | | THB | TRY | USD | ZAR |


Examples:

Geo

Description: Provides quick access for wan, lan, router, dns, mac, and ip geolocation data

Usage: geo [flag]

Examples:

Custom Geo Output => [all] [query] [city] [region] [country] [zip] [isp]

Example: geo -a 8.8.8.8 -o city,zip,isp

Gist

Description: Manage your gists with git and Github API v3

Usage: gist [command] [args]

Example:

Lyrics

Description: Fetch lyrics for a certain song.

Usage: lyrics [flags] or tool [-a] [arg] [-s] [arg]

Examples:

Meme

Description: A lightning fast meme generator

Usage: tool [flags] or tool [flags] [arguments]

Examples:

Movies

Description: Provides relevant information about a certain movie.

Usage: movies [flag] or movies [movieToSearch]

Examples:

Newton

Description: Performs numerical calculations all the way up to symbolic math parsing.

Usage: newton [operation] [expression] or newton [flag]

Operations Sample Expression Sample Result
Simplify [[2x2]+7]*[4x2] 8 x4 + 28 x2
Factor x2 + 2x x (x + 2)
Derive x2+2x 2 x + 2
Integrate x2+2x 1/3 x3 + x2 +C
Roots/Zeroes x2+2x 2, 0
Tangent 2~x3 12 x + -16 | (Finding tangent line when x=2 for expression x3)
Area 2:4~x3 60 | (Finding area under curve from 2 to 4 for expression x3)
Cos pi -1
Sin pi 0
Tan pi/4 1
ArcCos 1 0
ArcSin 0 0
ArcTan pi arcsin(pi)
Abs -2 2
Log 2~8 3 | (Log base 2 of eight)

Valid Symbols: + add - subtract [ left parenthesis (you must use brackets bash has a bultin for parenthesis) ] right parenthesis (you must use brackets bash has a bultin for parenthesis) * multiply / divide ^ power : between the range of left and right side (only for area under curve) ~ parameter on right side (only for area, tangent line and log)

Examples:

Pwned

Usage: pwned [email]

Description: Checks where an email account has been breached

* -u Update Bash-Snippet Tools

* -h Show the help

* -v Get the tool version

Examples:

* pwned emailtocheck@email.com

Qrify

Usage: qrify [stringtoturnintoqrcode]

Description: Converts strings or urls into a qr code.

* -u Update Bash-Snippet Tools

* -m Enable multiline support

* -f Save the QRCode to a file

* -d Decode the QR code from a PNG/GIF/JP(E)G file

* -h Show the help

* -v Get the tool version

Examples:

* qrify this is a test string

* qrify -m two \n lines

* qrify -f fileNameHere Insert what you want to encode here

* qrify github.com # notice no http:// or https:// this will fail

* qrify -d fileName.png

Short

Description: Unmasks shortended urls.

Usage: short [shortURL] or short [flag]

Example:

Siteciphers

Description: Checks the available ciphers for the SSL of an https site.

Usage: siteciphers [flag] or siteciphers [optionalDFlag] [website]

Examples:

Stocks

Description: Finds the latest information on a certain stock.

Usage: stocks [flag] or stocks [company/ticker]

Examples:

Taste

Description: A recommendation engine that provides 3 similar items based on some input topic. Taste also has the ability to provide information on the item of interest. Supports: shows, books, music, artists, movies, authors, games

Usage: taste [flag] [item]

Examples:

Todo

Description: A simplistic commandline todo list.

Usage: todo [flags] or todo [flags] [arguments]

Examples:

Transfer

Description: Quickly transfer files from the command line.

Usage: transfer [flags] or transfer [flag] [args] or transfer [filePathToUpload]

Examples:

Weather

Description: Provides a 3 day forecast on your current location or a specified location. With no flags Weather will default to your current location.

Usage: weather or weather [flag] or weather [country] or weather [city] [state]

Examples:

Ytview

Description: Search and play youtube videos right from the terminal.

Usage: ytview [flag] [string] or ytview [videoToSearch]

Examples:

Updating

With any of the installed tools you can automate the update by running it with the -u option or passing in update as the arguments

or

This will clone the repository and install the new versions of scripts that were installed, if you didn't install a certain tool this script will not install the new version of that tool.

Uninstalling

If you don't have the Bash-Snippets folder anymore clone the repository: git clone https://github.com/alexanderepstein/Bash-Snippets`

cd into the Bash-Snippets directory: cd Bash-Snippets

To go through a guided uninstall

AUTHOR

Alexander Epstein Github: https://github.com/alexanderepstein

Contributors

Jake Meyer Github: https://github.com/jakewmeyer

Linyos Torovoltos Github: https://gitbub.com/linyostorovovoltos

License

MIT License

Copyright (c) 2017 Alex Epstein

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

  1. April 2020
  2. bash-snippets(1)
================================================ FILE: bash-snippets.1.ronn ================================================ bash-snippets(1) -- A collection of small bash scripts for heavy terminal users ==== ## Tools ### Cheat Description: Cheatsheets for quick information about multiple programming languages along with terminal commands Usage: cheat [flags] [command] or cheat [flags] [programming language] [subject] * -s Does a search for last argument rather than looking for exact match * -i Case insensitive search * -b Word boundaries in search * -r Recursive search * -u Update Bash-Snippet Tools * -h Show the help * -v Get the tool version Special Pages: * hello Describes building the hello world program written in the language * list This lists all cheatsheets related to previous arg if none it lists all cheatsheets * learn Shows a learn-x-in-minutes language cheat sheet perfect for getting started with the language * 1line A collection of one-liners in this language * weirdness A collection of examples of weird things in this language Examples: * cheat rust hello * cheat -r -b -i go * cheat julia Functions * cheat -i go operators ### Cloudup Description: Backs up a users github repositories to your bitbucket account. With no flags cloudup will guide you through backing up a single repository Usage: cloudup [flags] or cloudup [flags] [listOfGHRepoNamesSplitBySpaces] * -p Upload the repositor(y)(ies) as private to bitbucket (must have private repo ability on bitbucket) * -a Backup all github repositories * -s Only backup repositories that you have created (no forks) (only works in conjunction with the -a flag) * -t Backup the repository with a timestamp added to the repostiory name (will always create a new unique bitbucket repo) * -u Update Bash-Snippet Tools * -h Show the help * -v Get the tool version Examples: * cloudup * cloudup -p -a * cloudup -p nameOfRepo1 nameOf Repo2 * cloudup nameOfRep ### Crypt Description: A wrapper around openssl that facilitates encrypting and decrypting files. Usage: crypt [flag] [inputFile] [outputFile] * -e Encrypt the inputFile and store it in the outputFil * -d Decrypt the inputFile and store it in the outputFil * -u Update Bash-Snippet Tools * -h Show the help * -v Get the tool version Examples: * crypt -e mySecretFile.txt myEncryptedFile.jpg (change filetype so default program is incorrect) * crypt -d myEncryptedFile.jpg thisIsNowDecrypted.txt (change filetype back so now default program is correct) ### CryptoCurrency Description: A realtime cryptocurrency converter. With no flags it will pull down the latest stats of the top 10 cryptos Usage: cryptocurrency or cryptocurrency [flag] or cryptocurrency [flag] [arg] * -o Utilize the old functionality of the tool * -f Fiat currency for conversions * -u Update Bash-Snippet Tools * -h Show the help * -v Get the tool version Examples: cryptocurrency -o cryptocurrency -f eur ### Currency Description: A realtime currency converter. With no flags it will guide you through the currency exchange Usage: currency or currency [flag] or currency [base] [exchangeTo] [amount] * -u Update Bash-Snippet Tools * -h Show the help * -v Get the tool version Supported Currencies: _______________________ | AUD | BGN | BRL | CAD | | CHF | CNY | CZK | DKK | | EUR | GBP | HKD | HRK | | HUF | IDR | ILS | INR | | JPY | KRW | MXN | MYR | | NOK | NZD | PHP | PLN | | RON | RUB | SEK | SGD | | THB | TRY | USD | ZAR | _______________________ Examples: * currency EUR USD 12.35 * currency ### Geo Description: Provides quick access for wan, lan, router, dns, mac, and ip geolocation data Usage: geo [flag] * -w Returns WAN IP * -l Returns LAN IP(s) * -r Returns Router IP * -d Returns DNS Nameserver * -m Returns MAC address for interface. Ex. eth0 * -g Returns Current IP Geodata Examples: * geo -g * geo -wlrdgm eth0 Custom Geo Output => [all] [query] [city] [region] [country] [zip] [isp] Example: geo -a 8.8.8.8 -o city,zip,isp * -o [options] Returns Specific Geodata * -a [address] For specific ip in -s * -v Returns Version * -h Returns Help Screen * -u Updates Bash-Snippets ### Gist Description: Manage your gists with git and Github API v3 Usage: gist [command] [args] * [star|all] List your gists, use 'star' as argument for your starred gists, 'all' or 'a' for both your and starred gists. Format for each line is: * fetch Update the local list of your gists, 'star' as argument for your starred gists * Show the path of local gist repo and do custom actions * new Create a new gist with files or STDIN * grep Grep gists by description, filename and content with a given pattern * tag Modify/List tags for a gist * tags List all tags and pinned tags * pin, Pin/Unpin tags, or filter gists with pinned tags * lan Filter gists or list gist with coding languages * detail Show the detail of a gist * edit Edit description for a gist * delete Delete gists by given indices * push Push changes by git * clean Clean local repos of removed gists * config Do configuration * user Get list of gists with a given Github user * github Import selected gist as a new Github repo * help Show the helper message Example: * gist (Show your gists) * gist tag (Show your gists with tags) * gist fetch (update the list of gists from github.com) * gist 3 (show the repo path of your 3rd gist, and do custom actions) * gist 3 --no-action (show the repo path of your 3rd gist, and do not perform actions) * gist new --desc bar foo (create a new gist with files and description) ### Lyrics Description: Fetch lyrics for a certain song. Usage: lyrics [flags] or tool [-a] [arg] [-s] [arg] * -a Artist of the song to fetch lyrics for * -s Song of the artist to fetch lyrics for * -f Export the lyrics to file rather than outputting to stdout * -u Update Bash-Snippet Tools * -h Show the help * -v Get the tool version Examples: * lyrics -a logic -s run it * lyrics -a logic -s run it -f ~/runItLyrics.txt ### Meme Description: A lightning fast meme generator Usage: tool [flags] or tool [flags] [arguments] * -u Update Bash-Snippet Tools * -h Show the help * -f Choose the output filename * -v Get the tool version Examples: * meme -f dogeMeme ### Movies Description: Provides relevant information about a certain movie. Usage: movies [flag] or movies [movieToSearch] * -u Update Bash-Snippet Tools * -h Show the help * -v Get the tool version * -d Show detailed information Examples: * movies Argo * movies Inception ### Newton Description: Performs numerical calculations all the way up to symbolic math parsing. Usage: newton [operation] [expression] or newton [flag] * -u Update Bash-Snippet Tools * -h Show the help * -v Get the tool version |Operations Sample Expression Sample Result| |---------------------------------------------------| |Simplify [[2x^2]+7]*[4x^2] 8 x^4 + 28 x^2 | |Factor x^2 + 2x x (x + 2) | |Derive x^2+2x 2 x + 2 | |Integrate x^2+2x 1/3 x^3 + x^2 +C| |Roots/Zeroes x^2+2x 2, 0 | |Tangent 2~x^3 12 x + -16 | (Finding tangent line when x=2 for expression x^3) |Area 2:4~x^3 60 | (Finding area under curve from 2 to 4 for expression x^3) |Cos pi -1 | |Sin pi 0 | |Tan pi/4 1 | |ArcCos 1 0 | |ArcSin 0 0 | |ArcTan pi arcsin(pi) | |Abs -2 2 | |Log 2~8 3 | (Log base 2 of eight) Valid Symbols: + add - subtract [ left parenthesis (you must use brackets bash has a bultin for parenthesis) ] right parenthesis (you must use brackets bash has a bultin for parenthesis) * multiply / divide ^ power : between the range of left and right side (only for area under curve) ~ parameter on right side (only for area, tangent line and log) Examples: * newton simplify [[2x^2]+7]*[4x^2] * movies derive x^2+2x ### Pwned Usage: pwned [email] Description: Checks where an email account has been breached * -u Update Bash-Snippet Tools * -h Show the help * -v Get the tool version Examples: * pwned emailtocheck@email.com ### Qrify Usage: qrify [stringtoturnintoqrcode] Description: Converts strings or urls into a qr code. * -u Update Bash-Snippet Tools * -m Enable multiline support * -f Save the QRCode to a file * -d Decode the QR code from a PNG/GIF/JP(E)G file * -h Show the help * -v Get the tool version Examples: * qrify this is a test string * qrify -m two \n lines * qrify -f fileNameHere Insert what you want to encode here * qrify github.com # notice no http:// or https:// this will fail * qrify -d fileName.png ### Short Description: Unmasks shortended urls. Usage: short [shortURL] or short [flag] * -e Expand the following URL * -s Shorten the following URL * -u Update Bash-Snippet Tools * -h Show the help * -v Get the tool version Example: * Input: short -e tinyurl.com/jhkj * Output: http://possiblemaliciouswebsiteornot.com * Input: short -s google.com * Output: http://ki.tc/23sd1d ### Siteciphers Description: Checks the available ciphers for the SSL of an https site. Usage: siteciphers [flag] or siteciphers [optionalDFlag] [website] * -u Update Bash-Snippet Tools * -h Show the help * -v Get the tool version * -d Set the delay between requests sent to the site (default is 1 sec) Examples: * siteciphers github.com * siteciphers -d 0.75 google.com ### Stocks Description: Finds the latest information on a certain stock. Usage: stocks [flag] or stocks [company/ticker] * -u Update Bash-Snippet Tools * -h Show the help * -v Get the tool version Examples: * stocks AAPL * stocks Tesla ### Taste Description: A recommendation engine that provides 3 similar items based on some input topic. Taste also has the ability to provide information on the item of interest. Supports: shows, books, music, artists, movies, authors, games Usage: taste [flag] [item] * -i Get more information on similar items * -s Get information on the item itself * -u Update Bash-Snippet Tools * -h Show the help * -v Get the tool version Examples: * taste -i Kendrick Lamar * taste Catcher in the Ry * taste -s Red Hot Chili Peppers ### Todo Description: A simplistic commandline todo list. Usage: todo [flags] or todo [flags] [arguments] * -c Clear all the current tasks * -r Remove the following task number * -g Get the current tasks * -a Add the following task * -u Update Bash-Snippet Tools * -h Show the help * -v Get the tool version Examples: * todo -a My very first task * todo -r 1 * todo -g * todo -c ### Transfer Description: Quickly transfer files from the command line. Usage: transfer [flags] or transfer [flag] [args] or transfer [filePathToUpload] * -d Download a single file * First arg: Output file directory * Second arg: File url id * Third arg: File name * -o Onetime file upload * -u Update Bash-Snippet Tools * -h Show the help * -v Get the tool version Examples: * transfer ~/fileToTransfer.txt * transfer ~/firstFileToTransfer.txt ~/secondFileToTransfer.txt # upload multiple files at once * transfer -d ~/outputDirectory fileID fileName * transfer -o ~/fileToTransfer.txt ### Weather Description: Provides a 3 day forecast on your current location or a specified location. With no flags Weather will default to your current location. Usage: weather or weather [flag] or weather [country] or weather [city] [state] * weather [optionalLocation] [i][M] get weather in imperial units, optional M means windspeed in m/s * weather [optionalLocation] [m][M] lowercase m gets weather in metric units, optional M means windspeed in m/s * weather [Moon] grabs the phase of the moon * -u Update Bash-Snippet Tools * -h Show the help * -v Get the tool version Examples: * weather * weather Paris m * weather Tokyo * weather Moon * weather mM ### Ytview Description: Search and play youtube videos right from the terminal. Usage: ytview [flag] [string] or ytview [videoToSearch] * -s Searches youtube * -c Shows the latest videos of a channel * -u Update Bash-Snippet Tools * -h Show the help * -v Get the tool version Examples: * ytview -s Family Guy Chicken Fight * ytview -c Numberphile ## Updating With any of the installed tools you can automate the update by running it with the -u option or passing in update as the arguments * stocks update or * stocks -u This will clone the repository and install the new versions of scripts that were installed, if you didn't install a certain tool this script will not install the new version of that tool. ## Uninstalling If you don't have the Bash-Snippets folder anymore clone the repository: git clone https://github.com/alexanderepstein/Bash-Snippets` cd into the Bash-Snippets directory: `cd Bash-Snippets` To go through a guided uninstall * ./uninstall.sh ## AUTHOR Alexander Epstein Github: https://github.com/alexanderepstein ## Contributors Jake Meyer Github: https://github.com/jakewmeyer Linyos Torovoltos Github: https://gitbub.com/linyostorovovoltos ## License MIT License Copyright (c) 2017 Alex Epstein Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: changelog.md ================================================
# Bash-Snippets Changelog ## Version 1.23.0 ## Changes * Added python3 support * Added new feature from rates.sx for cryptocurrency * Added new component bak2dvd * Fixed stocks script and pointing it to new api * Fixing Wlan IP on Mac for geo * Adding environment variable YTVIEWPLAYER for choice of default player for ytview
## Version 1.22.1
## Changes * Fix bugs in currency tool because of api changes * Fix bugs in cloudup tool because of api changes * Fixing movies tool * Fix bugs in meme tool * Fix default answer on install
## Version 1.22.0
## Changes * Adding bash-snippets gui component * Fixing bug in url shortener * Fixing old functionality cryptocurrency
## Version 1.21.0
## Changes * Fixing the exchange name for the stocks tool * Adding the memes component * Fixing locale error * Added pwned component * Adding one time file transfer to transfer component * Changing how cryptocurrency tool works now using rate.sx
## Version 1.20.0
## Changes * Brought back lyrics tool * Added shorten url functionality to short * Fixed the stocks api * Save QRCodes to an image file * Fixed bug in qrify for single-word strings * Adding mdfind functionality to ytview
## Version 1.19.2
## Changes * ytview for macOS can now use mpv * lyrics tool was removed, api is not available anymore
## Version 1.19.1
## Changes * Fixed bug in todo for task lists over 8 tasks * Fixing the endpoint in the short tool
## Version 1.19.0
### Changes * Adding BCH to cryptocurrencies tool * Adding lyrics component
## Version 1.18.1
### Changes * Changed how transfer uploads files * Upload multiple files with transfer * Get tasks after removal of tasks in todo * Bulk removal of tasks in todo * Removing bad echo from cloudup
## Version 1.18.0
### Changes * Added transfer component * Fixing fetch call across all tools * Changing progress echos for update * Run checkInternet only when needed (speeds up processes that don't need it) * Hiding the api help page in weather
## Version 1.17.3
### Changes * checkInternet now checks github.com over google.com * tools that don't need bc don't use it * tools that need bc can approximate without it * Fixing trailing quotation mark for newton on osx * Adding all option to uninstall
## Version 1.17.2
### Changes * Fixing where manpage is installed for linuxbrew * Updating weather usage and manpage
## Version 1.17.1
### Bugfixes * Fixing grabbing the prefix in homebrew install
## Version 1.17.0
### Changes * Adding ability to use m/s for windspeed in weather * Supporting httpie for all tools that work with it * Install for homebrew can now handle multiple tools on one line
## Version 1.16.2
### Changes * Adding back all argument to homebrew install
## Version 1.16.1
### Changes * Changed install script for homebrew * Added the -r option to newton
## Version 1.16.0
### Changes * Added cryptocurrency component * Added newton component * Changed WAN Call in geo
## Version 1.15.2
### Bugfixes * Installer path was preventing install
## Version 1.15.1
### Changes * Added --prefix option to installer for homebrew correctly
## Version 1.15.0
### Changes * Added -d option to movies * Updating extra tools if installed in main update pipeline
## Version 1.14.3
### Changes * Adding new progress echos to cloudup ### Bugfixes * Fixed bug in all tools using python for OSX where it would result caught in a segfault
## Version 1.14.2
### Bugfixes * Fixing bug where cloudup was incorrectly deleting the remote bitbucket repository.
## Version 1.14.1
### Bugfixes * Fixing issue in cloudup remote url was not set correctly if the ```-t``` option was not used * Fixing issue in cloudup where tags were causing conflicts, solved by deleting bitbucket repo first
## Version 1.14.0
### Changes * Shebang changed to ```/usr/bin/env bash``` for more portability * Todo has more error checking for bad input * Added the ```-s``` option to cloudup which will prevent the backup of forked repositories * Added the ```-t``` option to cloudup to give the user the ability to create a unique repo or just update the old one
## Version 1.13.2
### Changes * Updated installer not allow updates if bash-snippets was installed through package manager
## Version 1.13.1
### Changes * Preventing bad input in ```todo -r``` * Stocks was using unnecessary characters in the URL * Cloudup's private option now works * Cloudup's all option now looks to backup the first 10,000 repositories versus 100
## Version 1.13.0
### Changes * Added todo component ### Bugfixes * Forcing ytview to search in english
## Version 1.12.0
### Changes * Added siteciphers component ### Bugfixes * Crypt was still using only curl to get tags for update
## Version 1.11.1
### Changes * Now supporting the use of proxies * Typo fixes * Adding IMDB rating to movies tool ### Bugfixes * Suppressing ```source ~/.bash_profile``` error
## Version 1.11.1
### Bugfixes * Fixed issue in ytview where it was playing wrong video * Fixed wget check in qrify
## Version 1.11.0
### Changes * Adding manpage, view it with ```man bash-snippets```
## Version 1.10.1
### Changes * Cloudup's -a option is now functional ### Bugfixes * Cloudup only needs one temporary copy of the repository * Qrify had an issue where it couldn't handle more than one space * Cloudup now retains git history when it backs up to bitbucket * Fetch removed from qrify since it will not work
## Version 1.10.0
### Changes * Added qrify component ### Bugfixes * Bug in taste where the -i option was not working * Bug in all scripts that used python on OSX * Bug in taste script on OSX
## Version 1.9.0
### Changes * Added cloudup component ### Bugfixes * Fixing bug in ytview when search results are sparse
## Version 1.8.0
### Changes * Added ytview component ### Bugfixes * Using ```$@``` instead of ```$1 $2 $3...``` in all applicable scripts * Make call to python 2 explicit in all applicable scripts * Hiding the cheatsheet api help page from the user
## Version 1.7.0
### Changes * Added cheat component
## Version 1.6.0
### Changes * Added geo component
## Version 1.5.0
### Changes * Added short component ### Bugfixes * Sending errors in taste tool to /den/null * Taste tool only has one unique youtube link not three
## Version 1.4.0
# Changes * Added taste component
## Version 1.3.1
### Bugfixes * Fixing bug in currency where invalid exchangeTo wasn't handled correctly
## Version 1.3.0
### Changes * Now supporting wget, fetch and curl * Cleaning an echo on error for updating
## Version 1.2.1
### Changes * Check if curl is installed before using it * No sudo on error in update, just let user know they need to run the command as sudo * Changelog added ### Bugfixes * Setting user agent for curl to prevent issues from changes in ~/.curlrc
## Version 1.2.0
### Changes * Added help to each tool call with ```-h``` * Can now call weather with metric or imperial units * Can now get the moon phase from weather * Adding locale to weather so it will return in native language
## Version 1.1.1
### Changes * Now you can pass arguments to the weather tool to get weather of a location other then your own * Now you can pass arguments to the currency tool to bypass the guided input * The output for the currency tool is cleaner ### Bugfixes * Fixed bug in currency where exchange rate was not parsed correctly * Fixed bug in stocks where you could get lost in the tool by providing no input
## Version 1.1.0
### Changes * Facilitate updating by calling any of the tools with the -u option or update as the argument ex ```weather -u``` or ```weather update```
## Version 1.0.0
### Initial Release * Weather component added * Stocks component added * Movies component added * Currency component added * Crypt component added ================================================ FILE: cheat/cheat ================================================ #!/usr/bin/env bash # Author: Alexander Epstein https://github.com/alexanderepstein currentVersion="1.23.0" configuredClient="" ## rest of these variables are search flags search="0" insensitive="" recursive="" boundry="" ## This function determines which http get tool the system has installed and returns an error if there isnt one getConfiguredClient() { if command -v curl &>/dev/null; then configuredClient="curl" elif command -v wget &>/dev/null; then configuredClient="wget" elif command -v http &>/dev/null; then configuredClient="httpie" elif command -v fetch &>/dev/null; then configuredClient="fetch" else echo "Error: This tool requires either curl, wget, httpie or fetch to be installed." >&2 return 1 fi } ## Allows to call the users configured client without if statements everywhere httpGet() { case "$configuredClient" in curl) curl -A curl -s "$@" ;; wget) wget -qO- "$@" ;; httpie) http -b GET "$@" ;; fetch) fetch -q "$@" ;; esac } checkInternet() { httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request } update() { # Author: Alexander Epstein https://github.com/alexanderepstein # Update utility version 2.2.0 # To test the tool enter in the defualt values that are in the examples for each variable repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then echo "Error: update utility has not been configured correctly." >&2 exit 1 elif [[ $latestVersion == "" ]]; then echo "Error: no active internet connection" >&2 exit 1 else if [[ "$latestVersion" != "$currentVersion" ]]; then echo "Version $latestVersion available" echo -n "Do you wish to update $repositoryName [Y/n]: " read -r answer if [[ "$answer" == [Yy] ]]; then cd ~ || { echo 'Update Failed'; exit 1; } if [[ -d ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi echo -n "Downloading latest version of: $repositoryName." git clone -q "https://github.com/$githubUserName/$repositoryName" && touch .BSnippetsHiddenFile || { echo "Failure!"; exit 1; } & while [ ! -f .BSnippetsHiddenFile ]; do { echo -n "."; sleep 2; };done rm -f .BSnippetsHiddenFile echo "Success!" cd $repositoryName || { echo 'Update Failed'; exit 1; } git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit." chmod a+x install.sh #this might be necessary in your case but wasnt in mine. ./$nameOfInstallFile "update" || exit 1 cd .. rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; } else exit 1 fi else echo "$repositoryName is already the latest version" fi fi } usage() { cat <&2 exit 1 ;; h) usage exit 0 ;; v) echo "Version $currentVersion" exit 0 ;; u) checkInternet || exit 1 update exit 0 ;; i) insensitive="i" search="1" ;; b) boundry="b" search="1" ;; r) recursive="r" search="1" ;; s) search="1" ;; :) echo "Option -$OPTARG requires an argument." >&2 exit 1 ;; esac done ### This functions sets arg 1 and arg 2 to be unqique items after the options for arg; do if [[ $arg != "-r" && $arg != "-s" && $arg != "-b" && $arg != "-i" ]]; then if [ -z ${arg1+x} ]; then arg1=$arg fi if [ ! -z ${arg1+x} ]; then arg2=$arg fi fi done ## check for special pages before moving on checkSpecialPage "$arg1" 1 checkSpecialPage "$arg2" 2 if [[ $# == 0 ]]; then usage exit 0 elif [[ $1 == "update" ]]; then checkInternet || exit 1 update exit 0 elif [[ $1 == "help" || $1 == ":help" ]]; then ## shows the help and prevents the user from seeing cheat.sh/:help usage exit 0 else checkInternet || exit 1 if [[ $arg1 != $arg2 ]]; then ## if they equal each other that means there was no arg 2 supplied getCheatSheet "$arg1" "$arg2" exit 0 else getCheatSheet "$arg1" exit 0 fi exit 0 fi ================================================ FILE: cloudup/cloudup ================================================ #!/usr/bin/env bash # Author: Alexander Epstein https://github.com/alexanderepstein currentVersion="1.23.0" configuredClient="" private="0" ## state of private flag all="0" ## state of all flag if [ -d ~/temp ]; then rm -rf ~/temp; fi ## if the temp folder exists we want to delete it just in case it was left over from a fatal error source="0" tStamp="0" ## This function determines which http get tool the system has installed and returns an error if there isnt one getConfiguredClient() { if command -v curl &>/dev/null; then configuredClient="curl" elif command -v wget &>/dev/null; then configuredClient="wget" elif command -v fetch &>/dev/null; then configuredClient="fetch" else echo "Error: This tool requires either curl, wget, httpie or fetch to be installed." >&2 return 1 fi } ## Allows to call the users configured client without if statements everywhere httpGet() { case "$configuredClient" in curl) curl -A curl -s "$@" ;; wget) wget -qO- "$@" ;; fetch) fetch -q "$@" ;; esac } checkInternet() { httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request } update() { # Author: Alexander Epstein https://github.com/alexanderepstein # Update utility version 2.2.0 # To test the tool enter in the defualt values that are in the examples for each variable repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then echo "Error: update utility has not been configured correctly." >&2 exit 1 elif [[ $latestVersion == "" ]]; then echo "Error: no active internet connection" >&2 exit 1 else if [[ "$latestVersion" != "$currentVersion" ]]; then echo "Version $latestVersion available" echo -n "Do you wish to update $repositoryName [Y/n]: " read -r answer if [[ "$answer" == [Yy] ]]; then cd ~ || { echo 'Update Failed'; exit 1; } if [[ -d ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi echo -n "Downloading latest version of: $repositoryName." git clone -q "https://github.com/$githubUserName/$repositoryName" && touch .BSnippetsHiddenFile || { echo "Failure!"; exit 1; } & while [ ! -f .BSnippetsHiddenFile ]; do { echo -n "."; sleep 2; };done rm -f .BSnippetsHiddenFile echo "Success!" cd $repositoryName || { echo 'Update Failed'; exit 1; } git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit." chmod a+x install.sh #this might be necessary in your case but wasnt in mine. ./$nameOfInstallFile "update" || exit 1 cd .. rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; } else exit 1 fi else echo "$repositoryName is already the latest version" fi fi } ## This grabs the users bitbucket info could be improved by making sure username exists getBitbucketInfo() { echo -n 'Enter your Bitbucket username: ' read bbUsername if [[ $bbUsername == "1" ]]; then echo "Using github username as bitbucket username" bbUsername=$ghUsername fi echo -n 'Enter your Bitbucket password: ' read -s password # -s flag hides password text; echo echo } backupRepo() { cd ~/temp/github/"$repoName" || { echo "Fatal error"; return 1; } repoSlug=$(echo "$repoName" | tr '[:upper:]' '[:lower:]') if [[ $tStamp == "0" ]]; then { echo -n "Attempting to delete existing bitbucket repostiory..."; httpGet -X DELETE "https://$bbUsername:$password@api.bitbucket.org/1.0/repositories/$bbUsername/$repoSlug" > /dev/null || echo -n -e "Failure!\n"; echo -n -e "Success!\n"; }; fi ## if no timestamp then repo will not be unique we must look to delete old repo if [[ $private == "1" ]]; then echo -n "Creating private repository for $repoName..." else echo -n "Creating public repository for $repoName..." fi if [[ $tStamp == "1" ]]; then ## create the repository with a timestamp appended to repo name timestamp=$(date | tr " " _ | tr : _ ) ## we do this because it takes care of changes bitbucket would have made if [[ $private == "1" ]]; then # if so we will use --data is_private=true when creating repository httpGet --user "$bbUsername":"$password" https://api.bitbucket.org/1.0/repositories/ --data name="$repoName""$timestamp" --data is_private=true > /dev/null || { echo -n -e "Failure!\n"; echo "Error: creating the bitbucket repo failed, most likely due to an incorrect username or password."; return 1; } else httpGet --user "$bbUsername":"$password" https://api.bitbucket.org/1.0/repositories/ --data name="$repoName""$timestamp" > /dev/null || { echo -n -e "Failure!\n"; echo "Error: creating the bitbucket repo failed, most likely due to an incorrect username or password."; return 1; } fi echo -n -e "Success!\n" echo -n "Setting new remote url..." git remote set-url origin "https://$bbUsername:$password@bitbucket.org/$bbUsername/$repoName$timestamp.git" > /dev/null || { echo -n -e "Failure!\n"; return 1;} ## switch the remote over to bitbucket rather than github else # we are creating a reoo without a timestamp appended name if [[ $private == "1" ]]; then # if so we will use --data is_private=true when creating repository httpGet --user "$bbUsername":"$password" https://api.bitbucket.org/1.0/repositories/ --data name="$repoName" --data is_private=true > /dev/null || { echo -n -e "Failure!\n"; echo "Error: creating the bitbucket repo failed, most likely due to an incorrect username or password."; return 1; } else httpGet --user "$bbUsername":"$password" https://api.bitbucket.org/1.0/repositories/ --data name="$repoName" > /dev/null || { echo -n -e "Failure!\n"; echo "Error: creating the bitbucket repo failed, most likely due to an incorrect username or password."; return 1; } fi echo -n -e "Success!\n" echo -n "Setting new remote url..." git remote set-url origin "https://$bbUsername:$password@bitbucket.org/$bbUsername/$repoName.git" > /dev/null || { echo -n -e "Failure!\n"; return 1;} ## switch the remote over to bitbucket rather than github echo -n -e "Success!\n" fi echo -n "Uploading $repoName to bitbucket.." git push -q origin --all > /dev/null && touch ~/temp/github/.BSnippetsHiddenFile || { echo -n -e "Failure!\n"; touch -f ~/temp/github/.BSnippetsBrokenFile; return 1; } & ## pushes al files to github and most of the repo history while [[ ! -f ~/temp/github/.BSnippetsHiddenFile ]] ;do if [ -f ~/temp/github/.BSnippetsBrokenFile ];then return 1;fi && echo -n "." && sleep 2; done rm -f ~/temp/github/.BSnippetsHiddenFile echo -e -n "Success!\n" echo -n "Uploading the tags for $repoName.." git push -q origin --tags > /dev/null && touch ~/temp/github/.BSnippetsHiddenFile || { echo -n -e "Failure!\n"; touch -f ~/temp/github/.BSnippetsBrokenFile; return 1; } & ## have to push tags here since --tags and --all are mutually exclusive while [[ ! -f ~/temp/github/.BSnippetsHiddenFile ]] ;do if [ -f ~/temp/github/.BSnippetsBrokenFile ];then return 1;fi && echo -n "." && sleep 2; done rm -f ~/temp/github/.BSnippetsHiddenFile echo -e -n "Success!\n" rm -rf ~/temp #if we have succesfully backedup the repo we dion't need this anymore and if we do we will recreate it echo "Successfully backed up $repoName" } ## When cloudup is called with no flags getGitHubRepoInfo() { echo -n 'Enter the name of the repostiory to backup: ' read repoName } ## This grabs github user info could be improved upon by checking if user exists getGitHubUserInfo() { echo -n 'Enter your Github username: ' read ghUsername } ## function that handles cloning a repository it uses $ghUsername and $repoName cloneGitHubRepo() { echo -n "Cloning $repoName.." validRepo="false" for repo in "${repoNames[@]}"; do if [[ $repo == "$repoName" ]];then validRepo="true" && break; fi done if ! $validRepo;then { echo -n -e "Failure!\n"; echo "Github repostiory is not valid (either incorrect username or repository)"; return 1;}; fi mkdir ~/temp cd || { echo "Fatal error"; return 1; } mkdir ~/temp/github || { echo "Fatal error"; return 1; } cd ~/temp/github || { echo "Fatal error"; return 1; } git clone -q https://github.com/"$ghUsername"/"$repoName" && touch ~/temp/github/.BSnippetsHiddenFile || { touch ~/temp/github/.BSnippetsBrokenFile; echo -e -n "Failure!\n"; return 1;} & while [[ ! -f ~/temp/github/.BSnippetsHiddenFile ]] ;do if [ -f ~/temp/github/.BSnippetsBrokenFile ];then return 1;fi && echo -n "." && sleep 2; done rm -f ~/temp/github/.BSnippetsHiddenFile echo -n -e "Success!\n" } ## Grabs the last 100 updated repos and greps to grab the repository names and puts them in an array called repoNames getGithubRepoNames() { for pageNumber in {1..100}; do ## iterate through 100 possible pages response=$(httpGet "https://api.github.com/users/$ghUsername/repos?sort=updated&per_page=100&page=$pageNumber") ## grab the original response if [[ $pageNumber == "1" && ( $(echo "$response" | grep -Eo "Not Found") == "Not Found" || $response == "[' ']") ]];then { echo -e -n "Failure!"; echo "Github username is invalid"; return 1;};fi repoResponse=$(echo "$response" | grep -Eo '"full_name": "[ a-Z . \/ \\ 0-9 -- _ ]*' | sed s/'"full_name": "'/""/g | sed s:"$ghUsername"/:: ) ## extract the repo names from the response forkResponse=($(echo "$response" | grep -Eo '"fork": [a-Z]*' | cut -d " " -f 2 | sed s/"'"//g )) ## extract the fork status of each repo count=0 ## used to iterate through the fork statuses if [[ $repoResponse == "" ]]; then break; fi ## will only break if the page is empty for repo in $repoResponse; do ## go through each repo if [[ $source == "1" ]]; then ## if the user set the source flag if [[ ${forkResponse[$count]} == "false" ]]; then repoNames+=("$repo"); fi ## if they are the owner of the repository add it to the list of repoNames count=$(( $count + 1 )) ## increment the counter else ## the user didnt set the source flag repoNames+=("$repo") ## add all repos in repoResponse to repoNames fi done done } usage() { cat <&2 exit 1 ;; s) source="1" ;; p) private="1" ;; t) tStamp="1" ;; h) usage exit 0 ;; a) all="1" ;; v) echo "Version $currentVersion" exit 0 ;; u) checkInternet || exit 1 update exit 0 ;; :) echo "Option -$OPTARG requires an argument." >&2 exit 1 ;; esac done if [[ $source == "1" && $all == "0" ]]; then { echo "Error: the -s flag only works in conjunction with the -a flag."; exit 1; }; fi ## check if the source flag was used correctly (no need to have source flag when specifying the repositories) if [[ $configuredClient != "curl" ]]; then { echo "Error: to use cloudup without the -t option curl must be installed"; exit 1; }; fi ## we have to have the ability to delete an unique repo which is possible with curl -X DELETE if [[ $# == "1" ]]; then # check for keywords if [[ $1 == "update" ]]; then checkInternet || exit 1 update exit 0 elif [[ $1 == "help" ]]; then usage exit 0 fi fi checkInternet || exit 1 if [[ $all == "0" ]]; then if [[ ($private == "0" && $tStamp == "0" && $1 != "")]]; then ## checking for an arguments after possible flags if so then run through the arguments (repositories) and back them up getGitHubUserInfo || exit 1 getGithubRepoNames || exit 1 getBitbucketInfo || exit 1 for i in "$@"; do ## if private is not on as a flag start rpping through them repoName=$i echo "Starting to backup $repoName" cloneGitHubRepo || exit 1 backupRepo || { echo "Error: couldnt backup $repoName to bitbucket"; exit 1; } echo done exit 0 elif [[ ( $private == "0" && $tStamp == "0" && $1 == "" ) || ( $private == "1" && $tStamp == "0" && $2 == "" ) || ( $private == "0" && $tStamp == "1" && $2 == "" ) || ( $private == "1" && $tStamp == "1" && $3 == "" ) ]]; then ## check for empty arguments after all possible flags, this will intiate a guided backup getGitHubUserInfo || exit 1 getGithubRepoNames || exit 1 getGitHubRepoInfo || exit 1 getBitbucketInfo || exit 1 echo cloneGitHubRepo || exit 1 backupRepo || { echo "Error: couldnt backup $repoName to bitbucket"; exit 1; } exit 0 else ## flags are set but arguments are also provided firstArg=$(( $private + $tStamp + 1 )) getGitHubUserInfo || exit 1 getGithubRepoNames || exit 1 getBitbucketInfo || exit 1 for i in "${@:$firstArg}"; do repoName=$i echo "Starting to backup $repoName" cloneGitHubRepo || exit 1 backupRepo || { echo "Error: couldnt backup $repoName to bitbucket"; exit 1; } echo done exit 0 fi else getGitHubUserInfo || exit 1 getGithubRepoNames || exit 1 getBitbucketInfo || exit 1 echo for repo in "${repoNames[@]}"; do repoName=$repo echo "Starting to backup $repoName" cloneGitHubRepo || exit 1 backupRepo || { echo "Error: couldnt backup $repoName to bitbucket"; exit 1; } echo done echo "Successfully backed up all repositories" exit 0 fi ================================================ FILE: crypt/crypt ================================================ #!/usr/bin/env bash # Author: Alexander Epstein https://github.com/alexanderepstein currentVersion="1.23.0" state="" configuredClient="" checkOpenSSL() { if ! command -v openssl &>/dev/null; then echo "Error: to use this tool openssl must be installed" >&2 return 1 else return 0 fi } checkInternet() { httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request } ## This function determines which http get tool the system has installed and returns an error if there isnt one getConfiguredClient() { if command -v curl &>/dev/null; then configuredClient="curl" elif command -v wget &>/dev/null; then configuredClient="wget" elif command -v http &>/dev/null; then configuredClient="httpie" elif command -v fetch &>/dev/null; then configuredClient="fetch" else echo "Error: This tool requires either curl, wget, httpie or fetch to be installed." >&2 return 1 fi } ## Allows to call the users configured client without if statements everywhere httpGet() { case "$configuredClient" in curl) curl -A curl -s "$@" ;; wget) wget -qO- "$@" ;; httpie) http -b GET "$@" ;; fetch) fetch -q "$@" ;; esac } ## uses openssl aes 256 cbc encryption to encrypt file salting it with password designated by user encrypt() { echo "Encrypting $1..." openssl enc -aes-256-cbc -salt -a -in "$1" -out "$2" || { echo "File not found"; return 1; } echo "Successfully encrypted" } ## uses openssl aes 256 cbc decryption to decrypt file decrypt() { echo "Decrypting $1..." openssl enc -aes-256-cbc -d -a -in "$1" -out "$2" || { echo "File not found"; return 1; } echo "Successfully decrypted" } update() { # Author: Alexander Epstein https://github.com/alexanderepstein # Update utility version 2.2.0 # To test the tool enter in the defualt values that are in the examples for each variable repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then echo "Error: update utility has not been configured correctly." >&2 exit 1 elif [[ $latestVersion == "" ]]; then echo "Error: no active internet connection" >&2 exit 1 else if [[ "$latestVersion" != "$currentVersion" ]]; then echo "Version $latestVersion available" echo -n "Do you wish to update $repositoryName [Y/n]: " read -r answer if [[ "$answer" == [Yy] ]]; then cd ~ || { echo 'Update Failed'; exit 1; } if [[ -d ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi echo -n "Downloading latest version of: $repositoryName." git clone -q "https://github.com/$githubUserName/$repositoryName" && touch .BSnippetsHiddenFile || { echo "Failure!"; exit 1; } & while [ ! -f .BSnippetsHiddenFile ]; do { echo -n "."; sleep 2; };done rm -f .BSnippetsHiddenFile echo "Success!" cd $repositoryName || { echo 'Update Failed'; exit 1; } git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit." chmod a+x install.sh #this might be necessary in your case but wasnt in mine. ./$nameOfInstallFile "update" || exit 1 cd .. rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; } else exit 1 fi else echo "$repositoryName is already the latest version" fi fi } usage() { cat <&2 exit 1 fi if [[ $# -ne 3 ]]; then echo "Option -e needs and only accepts two arguments [file to encrypt] [output file]" >&2 exit 1 fi ;; \?) echo "Invalid option: -$OPTARG" >&2 exit 1 ;; d) ## when trying to decrypt run this if [[ $state != "encrypt" ]]; then state="decrypt" else echo "Error: the -e and -d options are mutally exclusive" >&2 exit 1 fi if [[ $# -ne 3 ]]; then echo "Option -d needs and only accepts two arguments [file to decrypt] [output file]" >&2 exit 1 fi ;; u) getConfiguredClient || exit 1 checkInternet || exit 1 update exit 0 ;; h) usage exit 0 ;; v) echo "Version $currentVersion" exit 0 ;; :) ## will run when no arguments are provided to to e or d options echo "Option -$OPTARG requires an argument." >&2 exit 1 ;; esac done if [[ $# == 0 ]]; then usage exit 0 elif [[ $1 == "update" ]]; then getConfiguredClient || exit 1 checkInternet || exit 1 update || exit 1 exit 0 elif [[ $1 == "help" ]]; then usage exit 0 elif [[ $state == "encrypt" ]]; then encrypt "$2" "$3" || exit 1 exit 0 elif [[ $state == "decrypt" ]]; then decrypt "$2" "$3" || exit 1 exit 0 fi ================================================ FILE: cryptocurrency/cryptocurrency ================================================ #!/usr/bin/env bash # Original Author: Jonas-Taha El Sesiy https://github.com/elsesiy # Modifications: Alexander Epstein unset base unset exchangeTo old="false" currentVersion="1.23.0" unset configuredClient ## This function determines which http get tool the system has installed and returns an error if there isnt one getConfiguredClient() { if command -v curl &>/dev/null; then configuredClient="curl" elif command -v wget &>/dev/null; then configuredClient="wget" elif command -v http &>/dev/null; then configuredClient="httpie" elif command -v fetch &>/dev/null; then configuredClient="fetch" else echo "Error: This tool requires either curl, wget, httpie or fetch to be installed." >&2 return 1 fi } ## Allows to call the users configured client without if statements everywhere httpGet() { case "$configuredClient" in curl) curl -A curl -s "$@" ;; wget) wget -qO- "$@" ;; httpie) http -b GET "$@" ;; fetch) fetch -q "$@" ;; esac } ## Top 10 cryptocurrencies as base checkValidCurrency() { if [[ $1 != "BTC" && $1 != "ETH" \ && $1 != "XRP" && $1 != "LTC" && $1 != "XEM" \ && $1 != "ETC" && $1 != "DASH" && $1 != "MIOTA" \ && $1 != "XMR" && $1 != "STRAT" && $1 != "BCH" ]]; then echo "1" else echo "0" fi } checkTargetCurrency() { if [[ $1 != "AUD" && $1 != "BRL" \ && $1 != "CAD" && $1 != "CHF" && $1 != "CNY" \ && $1 != "EUR" && $1 != "GBP" && $1 != "HKD" \ && $1 != "IDR" && $1 != "INR" && $1 != "JPY" && $1 != "KRW" \ && $1 != "MXN" && $1 != "RUB" && $1 != "USD" ]]; then echo "1" else echo "0" fi } ## Grabs the base currency from the user and validates it with all the possible currency ## types available on the API and guides user through input (doesnt take in arguments) getBase() { echo -n "What is the base currency: " read -r base base=$(echo "$base" | tr /a-z/ /A-Z/) if [[ $(checkValidCurrency "$base") == "1" ]]; then unset base echo "Invalid base currency" getBase fi } ## Checks base currency from the user and validates it with all the possible currency ## types available on the API (requires argument) checkBase() { base=$1 base=$(echo "$base" | tr /a-z/ /A-Z/) if [[ $(checkValidCurrency "$base") == "1" ]]; then unset base echo "Invalid base currency" exit 1 fi } # Matches the symbol to the appropriate ids regarding the API calling. transformBase() { case "$base" in "ETH") reqId="ethereum" ;; "BTC") reqId="bitcoin" ;; "XRP") reqId="ripple" ;; "LTC") reqId="litecoin" ;; "XEM") reqId="nem" ;; "ETC") reqId="ethereum-classic" ;; "DASH") reqId="dash" ;; "MIOTA") reqId="iota" ;; "XMR") reqId="monero" ;; "STRAT") reqId="stratis" ;; "BCH") reqId="bitcoin-cash" ;; esac } ## Grabs the exchange to currency from the user and validates it with all the possible currency ## types available on the API and guides user through input (doesnt take in arguments) getExchangeTo() { echo -n "What currency to exchange to: " read -r exchangeTo exchangeTo=$(echo "$exchangeTo" | tr /a-z/ /A-Z/) if [[ $(checkTargetCurrency "$exchangeTo") == "1" ]]; then echo "Invalid exchange currency" unset exchangeTo getExchangeTo fi } ## Grabs the exchange to currency from the user and validates it with all the possible currency ## types available on the API (requires arguments) checkExchangeTo() { exchangeTo=$1 exchangeTo=$(echo "$exchangeTo" | tr /a-z/ /A-Z/) if [[ $(checkTargetCurrency "$exchangeTo") == "1" ]]; then echo "Invalid exchange currency" unset exchangeTo exit 1 fi } ## Get the amount that will be exchanged and validate that the user has entered a number (decimals are allowed) ## doesnt take in argument, it guides user through input getAmount() { echo -n "What is the amount being exchanged: " read -r amount if [[ ! "$amount" =~ ^[0-9]+(\.[0-9]+)?$ ]]; then echo "The amount has to be a number" unset amount getAmount fi } ## Get the amount that will be exchanged ## validate that the user has entered a number (decimals are allowed and requires argument) checkAmount() { amount=$1 if [[ ! "$amount" =~ ^[0-9]+(\.[0-9]+)?$ ]]; then echo "The amount has to be a number" unset amount exit 1 fi } checkInternet() { httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request } ## Grabs the exchange rate and does the math for converting the currency convertCurrency() { exchangeTo=$(echo "$exchangeTo" | tr '[:upper:]' '[:lower:]') exchangeRate=$(httpGet "https://api.coinmarketcap.com/v1/ticker/$reqId/?convert=$exchangeTo" | grep -Eo "\"price_$exchangeTo\": \"[0-9 .]*" | sed s/"\"price_$exchangeTo\": \""//g) > /dev/null if ! command -v bc &>/dev/null; then oldRate=$exchangeRate exchangeRate=$(echo "$exchangeRate" | grep -Eo "^[0-9]*" ) amount=$(echo "$amount" | grep -Eo "^[0-9]*" ) exchangeAmount=$(( $exchangeRate * $amount )) exchangeRate=$oldRate else exchangeAmount=$( echo "$exchangeRate * $amount" | bc ) fi exchangeTo=$(echo "$exchangeTo" | tr '[:lower:]' '[:upper:]') cat <&2 exit 1 elif [[ $latestVersion == "" ]]; then echo "Error: no active internet connection" >&2 exit 1 else if [[ "$latestVersion" != "$currentVersion" ]]; then echo "Version $latestVersion available" echo -n "Do you wish to update $repositoryName [Y/n]: " read -r answer if [[ "$answer" == [Yy] ]]; then cd ~ || { echo 'Update Failed'; exit 1; } if [[ -d ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi echo -n "Downloading latest version of: $repositoryName." git clone -q "https://github.com/$githubUserName/$repositoryName" && touch .BSnippetsHiddenFile || { echo "Failure!"; exit 1; } & while [ ! -f .BSnippetsHiddenFile ]; do { echo -n "."; sleep 2; };done rm -f .BSnippetsHiddenFile echo "Success!" cd $repositoryName || { echo 'Update Failed'; exit 1; } git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit." chmod a+x install.sh #this might be necessary in your case but wasnt in mine. ./$nameOfInstallFile "update" || exit 1 cd .. rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; } else exit 1 fi else echo "$repositoryName is already the latest version" fi fi } usage() { cat <&2 exit 1 ;; c) currency=$OPTARG ;; h) usage exit 0 ;; f) fiat=$OPTARG ;; o) old="true" ;; v) echo "Version $currentVersion" exit 0 ;; u) checkInternet || exit 1 # check if we have a valid internet connection if this isnt true the rest of the script will not work so stop here update exit 0 ;; :) echo "Option -$OPTARG requires an argument." >&2 exit 1 ;; esac done if $old;then getConfiguredClient || exit 1 getBase # get base currency getExchangeTo # get exchange to currency getAmount # get the amount to be converted transformBase convertCurrency # grab the exhange rate and perform the conversion exit 0 fi if [[ $1 == "update" ]]; then getConfiguredClient || exit 1 checkInternet || exit 1 # check if we have a valid internet connection if this isnt true the rest of the script will not work so stop here update exit 0 elif [[ $1 == "help" ]]; then usage exit 0 fi getConfiguredClient || exit 1 checkInternet || exit 1 link="rate.sx" if [[ $fiat =~ [a-zA-Z] ]]; then link="$fiat.$link" fi if [[ $currency =~ [a-zA-Z] ]]; then link="$link/$currency" fi httpGet "$link" ================================================ FILE: currency/currency ================================================ #!/usr/bin/env bash # Author: Alexander Epstein https://github.com/alexanderepstein # Expanded: Rohit Goswami https://github.com/HaoZeke unset base unset exchangeTo currentVersion="1.23.0" unset configuredClient currencyCodes=(AUD BAM BGN BMD BND BRL CAD CHF CNY CZK DJF DKK EUR GBP HKD HRK HUF IDR ISK ILS INR JPY KRW MXN MYR NOK NZD PAB PHP PLN RON RUB SEK SGD THB TRY USD ZAR) ## This function determines which http get tool the system has installed and returns an error if there isnt one getConfiguredClient() { if command -v curl &>/dev/null; then configuredClient="curl" elif command -v wget &>/dev/null; then configuredClient="wget" elif command -v http &>/dev/null; then configuredClient="httpie" elif command -v fetch &>/dev/null; then configuredClient="fetch" else echo "Error: This tool requires either curl, wget, httpie or fetch to be installed." >&2 return 1 fi } peggedTo() { case "$@" in BAM) echo "EUR:1.95583" ;; BMD) echo "USD:1.0" ;; BND) echo "SGD:1.0" ;; DJF) echo "USD:177.721" ;; PAB) echo "USD:1.0" ;; *) echo "1" ;; esac } ## Allows to call the users configured client without if statements everywhere httpGet() { case "$configuredClient" in curl) curl -A curl -s "$@" ;; wget) wget -qO- "$@" ;; httpie) http -b GET "$@" ;; fetch) fetch -q "$@" ;; esac } checkValidCurrency() { if [[ "${currencyCodes[*]}" == *"$(echo "${@}" | tr -d '[:space:]')"* ]]; then echo "0" else echo "1" fi } ## Grabs the base currency from the user and validates it with all the possible currency ## types available on the API and guides user through input (doesnt take in arguments) getBase() { echo -n "What is the base currency: " read -r base base=$(echo "$base" | tr /a-z/ /A-Z/) if [[ $(checkValidCurrency "$base") == "1" ]]; then unset base echo "Invalid base currency" getBase fi } ## Checks base currency from the user and validates it with all the possible currency ## types available on the API (requires argument) checkBase() { base=$1 base=$(echo "$base" | tr /a-z/ /A-Z/) if [[ $(checkValidCurrency "$base") == "1" ]]; then unset base echo "Invalid base currency" exit 1 fi } ## Grabs the exchange to currency from the user and validates it with all the possible currency ## types available on the API and guides user through input (doesnt take in arguments) getExchangeTo() { echo -n "What currency to exchange to: " read -r exchangeTo exchangeTo=$(echo "$exchangeTo" | tr /a-z/ /A-Z/) if [[ $(checkValidCurrency "$exchangeTo") == "1" ]]; then echo "Invalid exchange currency" unset exchangeTo getExchangeTo fi } ## Grabs the exchange to currency from the user and validates it with all the possible currency ## types available on the API (requires arguments) checkExchangeTo() { exchangeTo=$1 exchangeTo=$(echo "$exchangeTo" | tr /a-z/ /A-Z/) if [[ $(checkValidCurrency "$exchangeTo") == "1" ]]; then echo "Invalid exchange currency" unset exchangeTo exit 1 fi } ## Get the amount that will be exchanged and validate that the user has entered a number (decimals are allowed) ## doesnt take in argument, it guides user through input getAmount() { echo -n "What is the amount being exchanged: " read -r amount if [[ ! "$amount" =~ ^[0-9]+(\.[0-9]+)?$ ]] then echo "The amount has to be a number" unset amount getAmount fi } ## Get the amount that will be exchanged ## validate that the user has entered a number (decimals are allowed and requires argument) checkAmount() { amount=$1 if [[ ! "$amount" =~ ^[0-9]+(\.[0-9]+)?$ ]] then echo "The amount has to be a number" unset amount exit 1 fi } checkInternet() { httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request } ## Grabs the exchange rate and does the math for converting the currency convertCurrency() { trueBase=$base trueTarget=$exchangeTo peggedBase=$( peggedTo "$base" ) peggedTarget=$( peggedTo "$exchangeTo" ) coef1="1" coef2="1" if [[ "$peggedBase" =~ ^[A-Z]+:[0-9.]+$ ]]; then trueBase=$(echo "$peggedBase" | grep -Eo "^[A-Z]*") coef1=$(echo "$peggedBase" | grep -Eo "[0-9.]*$") fi if [[ "$peggedTarget" =~ ^[A-Z]+:[0-9.]+$ ]]; then trueTarget=$(echo "$peggedTarget" | grep -Eo "^[A-Z]*") coef2=$(echo "$peggedTarget" | grep -Eo "[0-9.]*$") fi if [[ "$trueBase" == "$exchangeTo" || "$base" == "$trueTarget" ]]; then exchangeRate="1" else exchangeRate=$(httpGet "https://api.exchangerate-api.com/v4/latest/$trueBase" | grep -Eo "$trueTarget\":[0-9.]*" | grep -Eo "[0-9.]*") > /dev/null fi if ! command -v bc &>/dev/null; then exchangeRate=$(echo "$exchangeRate" | grep -Eo "^[0-9]*" ) amount=$(echo "$amount" | grep -Eo "^[0-9]*" ) coef1=$(echo "$coef1" | grep -Eo "^[0-9]*" ) exchangeRate=$(( exchangeRate / coef1 )) exchangeRate=$(( exchangeRate * coef2 )) exchangeAmount=$(( exchangeRate * amount )) else exchangeRate=$( echo "scale=8; $exchangeRate / $coef1" | bc ) exchangeRate=$( echo "$exchangeRate * $coef2" | bc ) exchangeAmount=$( echo "$exchangeRate * $amount" | bc ) fi cat <&2 exit 1 elif [[ $latestVersion == "" ]]; then echo "Error: no active internet connection" >&2 exit 1 else if [[ "$latestVersion" != "$currentVersion" ]]; then echo "Version $latestVersion available" echo -n "Do you wish to update $repositoryName [Y/n]: " read -r answer if [[ "$answer" == [Yy] ]]; then cd ~ || { echo 'Update Failed'; exit 1; } if [[ -d ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi echo -n "Downloading latest version of: $repositoryName." git clone -q "https://github.com/$githubUserName/$repositoryName" && touch .BSnippetsHiddenFile || { echo "Failure!"; exit 1; } & while [ ! -f .BSnippetsHiddenFile ]; do { echo -n "."; sleep 2; };done rm -f .BSnippetsHiddenFile echo "Success!" cd $repositoryName || { echo 'Update Failed'; exit 1; } git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit." chmod a+x install.sh #this might be necessary in your case but wasnt in mine. ./$nameOfInstallFile "update" || exit 1 cd .. rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; } else exit 1 fi else echo "$repositoryName is already the latest version" fi fi } usage() { cat <&2 exit 1 ;; h) usage exit 0 ;; v) echo "Version $currentVersion" exit 0 ;; u) checkInternet || exit 1 # check if we have a valid internet connection if this isnt true the rest of the script will not work so stop here update exit 0 ;; :) echo "Option -$OPTARG requires an argument." >&2 exit 1 ;; esac done if [[ $# == 0 ]]; then checkInternet || exit 1 # check if we have a valid internet connection if this isnt true the rest of the script will not work so stop here getBase # get base currency getExchangeTo # get exchange to currency getAmount # get the amount to be converted convertCurrency # grab the exhange rate and perform the conversion exit 0 elif [[ $# == "1" ]]; then if [[ $1 == "update" ]]; then update elif [[ $1 == "help" ]]; then usage else echo "Not a valid argument" usage exit 1 fi elif [[ $# == "2" ]]; then echo "Not a valid argument" usage exit 1 elif [[ $# == "3" ]]; then checkInternet || exit 1 # check if we have a valid internet connection if this isnt true the rest of the script will not work so stop here checkBase "$1" checkExchangeTo "$2" checkAmount "$3" convertCurrency exit 0 else echo "Error: too many arguments." fi ================================================ FILE: extras/Linux/maps/maps ================================================ #!/usr/bin/env bash # Author: Alexander Epstein https://github.com/alexanderepstein currentVersion="1.23.0" configuredClient="" directionsFlag="0" directionsMapFlag="0" staticMapFlag="0" source ~/.bash_profile 2> /dev/null ## allows grabbing enviornment variable MAPQUEST_API_KEY=$MAPQUEST_API_KEY if [ -d ~/temp ]; then rm -rf ~/temp; fi ## This function determines which http get tool the system has installed and returns an error if there isnt one getConfiguredClient() { if command -v curl &>/dev/null; then configuredClient="curl" elif command -v wget &>/dev/null; then configuredClient="wget" elif command -v http &>/dev/null; then configuredClient="httpie" elif command -v fetch &>/dev/null; then configuredClient="fetch" else echo "Error: This tool requires either curl, wget, httpie or fetch to be installed." >&2 return 1 fi } ## Allows to call the users configured client without if statements everywhere httpGet() { case "$configuredClient" in curl) curl -A curl -s "$@" ;; wget) wget -qO- "$@" ;; httpie) http -b GET "$@" ;; fetch) fetch -q "$@" ;; esac } checkInternet() { httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request } update() { # Author: Alexander Epstein https://github.com/alexanderepstein # Update utility version 2.2.0 # To test the tool enter in the defualt values that are in the examples for each variable repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then echo "Error: update utility has not been configured correctly." >&2 exit 1 elif [[ $latestVersion == "" ]]; then echo "Error: no active internet connection" >&2 exit 1 else if [[ "$latestVersion" != "$currentVersion" ]]; then echo "Version $latestVersion available" echo -n "Do you wish to update $repositoryName [Y/n]: " read -r answer if [[ "$answer" == [Yy] ]]; then cd ~ || { echo 'Update Failed'; exit 1; } if [[ -d ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi echo -n "Downloading latest version of: $repositoryName." git clone -q "https://github.com/$githubUserName/$repositoryName" && touch .BSnippetsHiddenFile || { echo "Failure!"; exit 1; } & while [ ! -f .BSnippetsHiddenFile ]; do { echo -n "."; sleep 2; };done rm -f .BSnippetsHiddenFile echo "Success!" cd $repositoryName || { echo 'Update Failed'; exit 1; } git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit." chmod a+x install.sh #this might be necessary in your case but wasnt in mine. ./$nameOfInstallFile "update" || exit 1 cd .. rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; } else exit 1 fi else echo "$repositoryName is already the latest version" fi fi } getDirections() { response=$(httpGet "https://www.mapquestapi.com/directions/v2/route?key=$MAPQUEST_API_KEY&from=$1&to=$2&outFormat=json&ambiguities=ignore&routeType=fastest&doReverseGeocode=false&enhancedNarrative=false&avoidTimedConditions=false") firstDirection=$(echo "$response" | grep -Eo "origNarrative\":\"[a-z A-Z -./0-9]*" | grep -Eo "[^origNarrative\":][a-z A-Z -./0-9]*") tempDirections=($(echo "$response" | grep -Eo "\"narrative\":\"[a-z A-Z -./0-9]*")) distances=($(echo "$response" | grep -Eo "distance\":[0-9]*[.][0-9]*" | grep -Eo "[^distance\":][0-9]*[.][0-9]*")) totalDist=${distances[0]} count="0" count="-1" temp=${tempDirections[0]} for direct in "${tempDirections[@]}"; do if [[ $(echo "$direct" | grep -Eo "narrative") == "narrative" ]]; then count=$(echo $count + 1 | bc) directions[$count]=$temp temp=$(echo "$direct" | grep -Eo "[^\"narrative:\"][a-z A-Z 0-9./]*" | sed s/'","iconUrl"'//g) else temp="$temp $direct" fi done #for distance in $tempDistances directions[0]=$firstDirection } getDirectionsMap() { echo "Generating route map from $unformattedFromLocation to $unformattedToLocation" mkdir ~/temp || return 1 httpGet "https://www.mapquestapi.com/staticmap/v5/map?start=$1&end=$2&size=600,400@2x&key=$MAPQUEST_API_KEY" >> ~/temp/routeImage.png || return 1 if [[ $(uname -s) == "Linux" ]]; then display ~/temp/routeImage.png > /dev/null || return 1 elif [[ $(uname -s) == "Darwin" ]]; then open ~/temp/routeImage.png > /dev/null fi rm -rf ~/temp > /dev/null } printDirections() { echo echo "From $unformattedFromLocation to $unformattedToLocation ($totalDist mi)" echo "===================================================" count=0 for direct in "${directions[@]}"; do if [ $count -ne 0 ]; then echo -n "$(echo $count | bc)). "; fi if [[ $direct != "" ]]; then # sometimes original Narrative is blank direct="$direct (${distances[$(echo $count + 1 | bc)]} mi)" if [ $count -ne 0 ]; then echo "$direct"; fi count=$(echo $count + 1 | bc) fi done echo "Welcome to $unformattedToLocation" echo "===================================================" echo } getLocations() { echo -n "Enter your starting location: " read fromLocation echo -n "Enter your destination: " read toLocation unformattedFromLocation=$fromLocation unformattedToLocation=$toLocation fromLocation=$(echo "$fromLocation" | sed s/','/"+"/g | sed s/' '/"+"/g ) toLocation=$(echo "$toLocation" | sed s/','/"+"/g | sed s/' '/"+"/g ) } checkImagemagick() { if [[ $(uname -s) == "Linux" ]]; then if ! command -v display &>/dev/null; then echo "Error: you need to install imagemagick to use map features." &>2 return 1 else return 0 fi else return 0 fi } getMapLocation() { echo -n "Enter the city or address you want to generate a map for: " read mapLocation echo "Generating static map for $mapLocation" mapLocation=$(echo "$mapLocation" | sed s/','/"+"/g | sed s/' '/"+"/g ) } getStaticMap() { mkdir ~/temp || return 1 httpGet "https://www.mapquestapi.com/staticmap/v5/map?key=$MAPQUEST_API_KEY¢er=$1&zoom=15&type=hyb&size=600,400@2x" >> ~/temp/mapImage.png || return 1 if [[ $(uname -s) == "Linux" ]]; then display ~/temp/mapImage.png > /dev/null || return 1 elif [[ $(uname -s) == "Darwin" ]]; then open ~/temp/mapImage.png > /dev/null || return 1 fi rm -rf ~/temp > /dev/null || return 1 } usage() { cat <&2 exit 1 ;; h) usage exit 0 ;; d) directionsFlag="1" ;; m) staticMapFlag="1" ;; r) directionsMapFlag="1" ;; v) echo "Version $currentVersion" exit 0 ;; u) checkInternet || exit 1 update exit 0 ;; :) echo "Option -$OPTARG requires an argument." >&2 exit 1 ;; esac done if [[ $directionsMapFlag == "1" && $directionsFlag == "0" ]]; then { echo "Error the -r flag only works in conjunction with the -d flag."; exit 1; }; fi if [[ $# == 0 ]]; then usage exit 0 elif [[ $# == "1" ]]; then if [[ $1 == "update" ]]; then checkInternet || exit 1 update exit 0 elif [[ $1 == "help" ]]; then usage exit 0 fi fi checkInternet || exit 1 if [[ $directionsFlag == "0" && $staticMapFlag == "1" ]]; then checkImagemagick || exit 1 getMapLocation || exit 1 getStaticMap "$mapLocation" || exit 1 elif [[ $directionsFlag == "1" ]]; then getLocations || exit 1 getDirections "$fromLocation" "$toLocation" || exit 1 printDirections "$fromLocation" "$toLocation" || exit 1 checkImagemagick || exit 1 if [[ $directionsMapFlag == "1" ]]; then getDirectionsMap "$fromLocation" "$toLocation" || exit 1; fi if [[ $staticMapFlag = "1" ]]; then echo "Generating static map for $unformattedFromLocation" && getStaticMap "$fromLocation" || exit 1 echo "Generating static map for $unformattedToLocation" && getStaticMap "$toLocation" || exit 1 fi fi ================================================ FILE: extras/README.md ================================================
# Bash-Snippets Extras
## Why are these here? If there is a tool in this folder that means it is not part of the main installer pipeline It was removed or never made it to the pipeline only for two possible reasons: * It is platform dependent meaning it doesn't work the same on all \*nix machines * It had many dependencies that aren't native to all forms of \*nix ## Can I install these & is it safe Yes you can install these, only tools that are considered to be fully functional will make it here. Just make sure you only install extras for the correct platform and if they require dependencies make sure to install them (although the tool itself should remind you of this) ## Install To install the tool just ```cd``` into the folder of the tool and run ```cp toolNameGoesHere /usr/local/bin || echo "Run the install as sudo" ``` ## Uninstall To uninstall the tool just run ```rm -f /usr/local/bin/toolNameGoesHere || echo "Run the uninstall as sudo" ```. Notice that the recursive flag is not set so even if you accidentally go to remove ```/usr/local/bin``` the flags will not let you delete the directory. ## Platform Specific Tools ### Linux #### Maps * Provides driving directions from a certain location to another * Generates a route map of the trip and displays it * Generates maps of the from and to locations and displays them * The map functions require imagemagick to be installed ### OSX None for now ## Dependent tools None for now ## License MIT License Copyright (c) 2017 Alex Epstein Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: geo/geo ================================================ #!/usr/bin/env bash # Bash utility for getting specific network info # Author: Jake Meyer # Github: https://github.com/jakewmeyer currentVersion="1.23.0" configuredClient="" ## This function determines which http get tool the system has installed and returns an error if there isnt one getConfiguredClient() { if command -v curl &>/dev/null; then configuredClient="curl" elif command -v wget &>/dev/null; then configuredClient="wget" elif command -v http &>/dev/null; then configuredClient="httpie" elif command -v fetch &>/dev/null; then configuredClient="fetch" else echo "Error: This tool requires either curl, wget, httpie or fetch to be installed." >&2 return 1 fi } ## Allows to call the users configured client without if statements everywhere httpGet() { case "$configuredClient" in curl) curl -A curl -s "$@" ;; wget) wget -qO- "$@" ;; httpie) http -b GET "$@" ;; fetch) fetch -q "$@" ;; esac } # Parse arguments passed + help formatting usage() { cat < [all] [query] [city] [region] [country] [zip] [isp] Example: geo -a 8.8.8.8 -o city,zip,isp -o [options] Returns Specific Geodata -a [address] For specific IP in -s -v Returns Version -h Returns Help Screen -u Updates Bash-Snippets EOF exit } # Displays version number version() { echo "Version $currentVersion" } # Fetches WAN IP address wan_search() { httpGet https://api.ipify.org } # Fetches current LAN IP address lan_search() { if [ "$(uname)" = "Darwin" ]; then ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1' elif [ "$(uname -s)" = "Linux" ]; then ip addr show | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1' else echo "OS not supported" exit 1 fi } # Fetches Router ip address router_search() { if [ "$(uname)" = "Darwin" ]; then netstat -rn | grep default | head -1 | awk '{print$2}' elif [ "$(uname -s)" = "Linux" ]; then ip route | grep ^default'\s'via | head -1 | awk '{print$3}' else echo "OS not supported" exit 1 fi } # Fetches DNS nameserver dns_search() { if [ "$(uname)" = "Darwin" ]; then grep -i nameserver /etc/resolv.conf |head -n1|cut -d ' ' -f2 elif [ "$(uname -s)" = "Linux" ]; then cat /etc/resolv.conf | grep -i ^nameserver | cut -d ' ' -f2 else echo "OS not supported" exit 1 fi } # Fetches MAC address of mac_search() { if [ "$(uname)" = "Darwin" ]; then ifconfig "$MAC" | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}' elif [ "$(uname -s)" = "Linux" ]; then ip addr show "$MAC" | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}' | grep -v ff: else echo "OS not supported" exit 1 fi } # Fetches current geodata based on ip geodata_search() { httpGet "http://ip-api.com/line/?fields=query,city,region,country,zip,isp" } # Fetches specific geodata based on args specific_geo() { if [ "$OPTIONS" = "all" ]; then httpGet "http://ip-api.com/line/${ADDRESS}?fields=query,city,region,country,zip,isp" else httpGet "http://ip-api.com/line/${ADDRESS}?fields=${OPTIONS}" fi } update() { # Author: Alexander Epstein https://github.com/alexanderepstein # Update utility version 2.2.0 # To test the tool enter in the defualt values that are in the examples for each variable repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then echo "Error: update utility has not been configured correctly." >&2 exit 1 elif [[ $latestVersion == "" ]]; then echo "Error: no active internet connection" >&2 exit 1 else if [[ "$latestVersion" != "$currentVersion" ]]; then echo "Version $latestVersion available" echo -n "Do you wish to update $repositoryName [Y/n]: " read -r answer if [[ "$answer" == [Yy] ]]; then cd ~ || { echo 'Update Failed'; exit 1; } if [[ -d ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi echo -n "Downloading latest version of: $repositoryName." git clone -q "https://github.com/$githubUserName/$repositoryName" && touch .BSnippetsHiddenFile || { echo "Failure!"; exit 1; } & while [ ! -f .BSnippetsHiddenFile ]; do { echo -n "."; sleep 2; };done rm -f .BSnippetsHiddenFile echo "Success!" cd $repositoryName || { echo 'Update Failed'; exit 1; } git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit." chmod a+x install.sh #this might be necessary in your case but wasnt in mine. ./$nameOfInstallFile "update" || exit 1 cd .. rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; } else exit 1 fi else echo "$repositoryName is already the latest version" fi fi } checkInternet() { httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request } # Option parsing "controller" optspec="uwlrdm:go:a:vh*:" while getopts "$optspec" optchar; do case "${optchar}" in w) getConfiguredClient && checkInternet && wan_search || exit 1 ;; l) lan_search ;; r) router_search ;; d) dns_search ;; m) MAC=$OPTARG mac_search ;; g) getConfiguredClient && checkInternet && geodata_search || exit 1 ;; a) ADDRESS=$OPTARG ;; o) getConfiguredClient && checkInternet && OPTIONS=$OPTARG specific_geo || exit 1 ;; v) version ;; h) usage ;; u) getConfiguredClient && checkInternet && update || exit 1 ;; *) usage ;; esac done # Makes geo command default to help screen for usability if [ $# -eq 0 ]; then usage exit 0 elif [[ $1 == "update" ]]; then getConfiguredClient && checkInternet && update || exit 1 elif [[ $1 == "help" ]]; then usage exit 0 fi ================================================ FILE: gist/README.md ================================================ # gist - Manage your gist like a pro All your notes, scripts, config files and snippets deserve version control and tagging! `gist` is a simple bash script for gist management, lite and dependency-free! Use it to boost your coding workflow. - [Getting Started](#Getting-Started) - [Basic Commands](#Basic-Commands) - [Update and clone gists from Github](#Update-and-clone-gists-from-Github) - [List your gists](#List-your-gists) - [Create a new gist](#Create-a-new-gist) - [Modify a gist](#Modify-a-gist) - [Clean unnecessary local repos](#Clean-unnecessary-local-repos) - [Configuration](#Configuration) - [Filter gists](#Filter-gists) - [Filter by tags](#Filter-by-tags) - [Filter by file languages](#Filter-by-file-languages) - [Filter by pattern](#Filter-by-pattern) - [Tips](#Tips) - [Filter gists with pipe](#Filter-gists-with-pipe) - [Git Workflow](#Git-Workflow) - [Useful action for gist repo](#Useful-action-for-gist-repo) - [Suppress action](#Suppress-action) - [Suppress hint](#Suppress-hint) ## Getting Started ```bash # Install script curl -fsSL https://raw.githubusercontent.com/typebrook/gist/master/install.sh | bash # Fetch your gists and clone them into ~/gist as git repos gist fetch # List your gists gist # Create a new gist gist new # Create private gist with files 'foo' and 'bar' gist new -p foo bar # Check information of your third gist gist detail 3 # Get the path and cd to cloned repo with subshell gist 3 # List your gists with tags instead of URL gist tag # Add tags to your third gist gist tag 3 # Update the description of your third gist gist edit 3 # Push changes in your third gist to the remote repo gist push 3 # Delete gists with indices 3, 4 and 5 gist delete 3 4 5 # Or use Brace Expansion gist delete {3..5} # Export your third gist as a new Github repo with web page gist github 3 # For more detail, read the helper message gist help ``` ## Basic Commands ### Update and clone gists from Github Run `gist fetch` to fetch your all gists with Github API and keep short information for each gist in a index file inside a given folder. (default to `~/gist/index`) - Automatically Clone/Pull each gist with git into a given folder. (default to `~/gist/`) - Run `gist fetch star` to fetch you starred gist - If token is not being set, then you cannot fetch your private gist ### List your gists Run `gist` to read index file (default to `~/gist/index`) and list your gists with the following format: ``` ``` like the following: ![](https://i.imgur.com/ZCLGZLW.png) - Use `gist star` to show your starred gists - Use `gist all` to show your and starred gists - Index with prefix `s` is a starred gist, index with prefix `p` is a private gist - There are colorful hints for each gist in the following cases: - **working** Some changes are made locally but not yet do `git commit`, or you are not in `master` branch - **ahead** Your local **HEAD** is yet to be applied to upstream - **outdated** Your local **HEAD** is differs from the last fetched gists, do `gist fetch` to refresh index file and pull if needed ### Create a new gist Run `gist new` to create a new gist - You can create a new gist with 3 different ways: 1. type the content by hand, run `gist new` 2. use existing files, run `gist new ...` 3. from STDIN, like ` | gist new` - You can specify filename with `--file`, and description with `--desc`, like `gist new --file new --desc 'a new gist'` - If you don't specify filename or description, a prompt will shows up! ### Modify a gist Run `gist ` to enter sub-shell with working directory of the given gist index (by default action). You can do some trick with custom action.(See [action](#action) and [Tips](#Tips)) Since now a gist is a local cloned repo, it is your business to do git commit and git push. Use `gist push ` is not recommended. ### Clean unnecessary local repos Say you delete gists with command `gist delete ...`, the local git repositories are still at `~/gist/`. Run `gist clean` to move them into `/tmp` ## Configuration `gist` stores your configuraion inside `~/.config/gist.conf`, with `=` format for each line. And just do `source ~/.config/gist.conf` at runtime. `~/.config/gist.conf` is created automatically when you run `gist` at the first time, it only allows current user to read and write (permission 600). Valid keys are [`user`](#user), [`token`](#token), [`folder`](#folder), [`auto_sync`](#auto_sync), [`action`](#action), [`EDITOR`](#EDITOR), [`protocol`](#protocol) and [`show_untagged`](#show_untagged). Use the following commands to set value: ``` bash # Set key with a given value gist config # Remove current value from a key gist config # Or just modify ~/.config/gist.conf directly gist config ``` Each key is for the following use cases: ### user Your Github username If you use command which needs username and `user` is not being set, a prompt will shows up and requires your username and API [`token`](#token). Use `gist config user ` to set the value if needed. ### token Your Github API token for the given username. It's scope should be with `gist`. If you use command which needs it and it is not being set, A prompt will shows up and requires it. You can choose going to web page to create a new token, or just input an existing one directly. Use `gist config toekn ` to set the value if needed. ### folder **[Optional]** The folder you stores index file and git repos for each your gists and starred gists. Default to `~/gist/` if not being set. Use `gist config folder ` to set the value if needed. ### auto_sync **[Optional]** Automatically clone/update your gists and starred gists as git repos when doing `gist fetch`. Default to be `true`. Use `gist config auto_sync false` to disable this feature. ### action **[Optional]** A custom action is performed when you do `gist ` (like `gist 3` for your third gist). If is being set, `gist` will `cd` to the cloned repo, and just simply use `eval` to perform action. For example, you can use the following command to **print the filename and its content of all files inside the given gist** ```bash gist config action 'tail -n +1 *' ``` If action is not being set, then a default action will be performed: ```bash # Enter sub-shell with current shell or bash ${SHELL:-bash} ``` Also, if you run `gist ` with `--no-action`(or `-n`), then action would be ignored. ### EDITOR **[Optional]** Editor to open `~/.config/gist.conf`. Default to be `vi` . For example, use `gist config EDITOR code` to use VSCode instead. ### protocol **[Optional]** Protocol to clone git repo. Default to be `HTTPS` Valid values are: - https - ssh For example, use `gist config protocol ssh` to use SSH protocol instead. ### show_untagged **[Optional]** Whether to show untagged gists when using [`gist tag`](#List-gists-with-tags). Default to be `true` Use `gist config show_untagged false` to disable this feature. ## Filter gists ### Filter by tags `gist` treats **trailing hashtags** inside gist description as tags. For example, if a description is: ``` [Title] this is description #tag1 #tag2 ``` When [`gist`](#List-your-gists) is performed, it only display description with part: `[Title] this is description`, and treat the trailing hashtags as tags of a gist. #### Tag a gist You can use the following command to add/remove tags: ```bash # tag your third gist gist tag 3 ``` After it is finished, `gist` just calls Github API to apply new description onto the given gist. #### List gists with tags Use sub-command `tag` to list gists with tags instead of URLs. ```bash # show tags for your gists gist tag ``` ![](https://i.imgur.com/6IqxQjA.png) #### Filter gists with tags If arguments after `gist tag` are not indices of gist, then they will be treated as tag values. The output will be a list of gists with those tags ```bash # Filter gists with tag1 and tag2 gist tag tag1 tag2 ``` ![](https://i.imgur.com/rchqMN1.png) You can also use regex pattern as tag value: ```bash # only show tagged gists gist tag .+ ``` #### Show existing tags Use sub-command `tags` to show existing tags and pinned tags. They are sorted alphabetically. ```bash gist tags ``` ![](https://i.imgur.com/PuwmaK4.png) #### Pin/Unpin tags Say you are working with gists with some meaningful tags. You can use sub-command `pin` to pin them, and filter your gists with pinned tags ```bash # Pin tag1 and tag2, If a tag is pinned, then unpin it gist pin tag1 tag2 # Disply gists with pinned tags gist pin ``` ![](https://i.imgur.com/LuEjNry.png) ### Filter by pattern You can search gists with pattern in description, filename or file contents with sub-command `grep` ```bash # search by a simple string gist grep string # search by a pattern(heading string in a line) gist grep '^string' ``` ### Filter by file languages #### List gists with languages You can use sub-command `lan` to List gists with file languages instead of URLs. ```bash # show languages for your gists gist lan ``` ![](https://i.imgur.com/QAS7ZRE.png) #### Filter gists with languages ```bash # Filter gists with files in Shell and Yaml format gist lan LANGUAGE1 LANGUAGE2... ``` ![](https://i.imgur.com/tKI5KND.png) ### Index Range You can specify the range of indices, works both on your owned gists and starred gists. ```bash # only show gists with index 5 to 10 gist 5-10 # show gists from index 5 gist 5- # show starred gists only to index s10 gist -s10 # only show gists with index 1 to 20 seq 20 | gist ``` ## Tips ### Filter gists with pipe If `STDIN` is from a pipe, then `gist` will only process gists with **indices in the first column**. So, you can concatenate the output of each sub-command. ```bash # only show gists with index 1 to 20 seq 20 | gist # List starred gist with Yaml file gist star | gist lan Yaml # Only List gists with tag1, pattern1 in description/filenames/contents and contains shell script gist tag tag1 | gist grep pattern1 | gist lan SHELL ``` ### Git Workflow Each gist is a git repository. Although there are some limits on `git push`, like sub-directory is prohibited. But guess what? 1. Push another branch to `github.com` is allowed. 2. Push tags is also allowed. And like repos in `github.com`, you can get source file by tag with URL: ``` https://codeload.github.com/gist//tar.gz/ ``` ### Useful action for gist repo I strongly recommend using [`tig`](https://github.com/jonas/tig) as your custom [action](#action). It is the most powerful git CLI tool as far as I know, and also easy to get in most of the Linux distros or Homebrew for mac. Give it a try! If [`tig`](https://github.com/jonas/tig) is installed, run the following command to configure it as custom action: ```bash gist config action 'tig -all' ``` `tig` interface for history diagram: ![](https://i.imgur.com/ju37MgW.png) ### Suppress action If [`action`](#action) is not being set, you will enter sub-shell by default. If you want suppress it and do not want to type `--no-action` every time, just use command `ture` to do nothing. ``` gist config action 'true' ``` ### Suppress hint There are several environment variables or arguments can suppress hint or user confirm, like: ```bash # List gists without hint hint=false gist # Just print the repo path with a given index gist 3 --no-action # Or shorter argument gist 3 -n # Delete your third gist without confirmation gist delete 3 --force ``` ================================================ FILE: gist/gist ================================================ #!/usr/bin/env bash # # Author: Hsieh Chin Fan (typebrook) # License: MIT # https://gist.github.com/typebrook/b0d2e7e67aa50298fdf8111ae7466b56 # # -- # gist # Description: Manage your gists with git and Github API v3 # Usage: gist [command] [] # # [star|s|all|a] List your gists, use 'star' or 's' for your starred gists, # 'all' or 'a' for both your and starred gists. Format for each line is: # # fetch, f [star|s] Update the local list of your gists, 'star' for your starred gists # [-n|--no-action] Show the path of local gist repo and do custom actions(enter sub-shell by default) # new, n [-d |--desc ] [-p] ... create a new gist with files # new, n [-d |--desc ] [-p] [-f|--file ] create a new gist from STDIN # grep, g Grep gists by description, filename and content with a given pattern # tag, t Modify tags for a gist # tag, t ... Grep gists with tags # tag, t List gist with tags and pinned tags # tags, tt List all tags and pinned tags # pin, p ... Pin/Unpin tags # pin, p Grep gists with pinned tags # lan, l ... Grep gists with languages # lan, l List gist with languages of files # detail, d Show the detail of a gist # edit, e ["NEW_DESCRIPTRION"] Edit a gist's description # delete, D ... [--force] Delete gists by given indices # push, P Push changes by git (well, better to make commit by youself) # clean, C Clean local repos of removed gists # config, c [token|user|folder|auto_sync|EDITOR|action|protocol|show_untagged [value]] Do configuration # user, u Get list of gists with a given Github user # github, G Export selected gist as a new Github repo # help, h Show this help message # version Get the tool version # update Update Bash-Snippet Tools # # Example: # gist fetch (update the list of gists from github.com) # gist (Show your gists) # gist 3 (show the repo path of your 3rd gist, and do custom actions) # gist 3 --no-action (show the repo path of your 3rd gist, and do not perform actions) # gist new foo bari (create a new gist with files foo and bar) # gist tag (Show your gists with tags) # gist tag 3 (Add tags to your 3rd gist) # gist tag .+ (show tagged gists) # # Since now a gist is a local cloned repo # It is your business to do git commit and git push # TODO Named temp file # TODO feature to exclude tag-value or grep-string # TODO codebase statistics, like C++ or something # TODO migrate to gh-page, with install.sh and check_md5 in README currentVersion="1.23.0" configuredClient="" NAME=${GISTSCRIPT:-$(basename "$0")} #show hint and helper message with current script name GITHUB_API=https://api.github.com CONFIG=~/.config/gist.conf; mkdir -p ~/.config INDEX_FORMAT=('index' 'url' 'tags_string' 'blob_code' 'file_array' 'file_num' 'comment_num' 'author' 'created_at' 'updated_at' 'description') TAG_CHAR='-_[:alnum:]' if [[ ! -t 0 ]]; then INPUT=$(cat) export mark=. else export mark=[^s] # By defaut, only process user's gists, not starred gist fi # Default configuration [[ ! -t 1 && -z $hint ]] && hint=false auto_sync=true # automatically clone the gist repo protocol=https # Shell configuration set -o pipefail [[ $TRACE == 'true' ]] && set -x # clean temporary files tmp_dir=$(mktemp -d) trap "[[ '$DEBUG' == 'true' ]] && find $tmp_dir -type f | xargs tail -n +1 > log; rm -r $tmp_dir" EXIT # Mac compatibility tmp_file() { if [[ $(uname) == Darwin ]]; then file=$(mktemp) && mv $(mktemp) "$tmp_dir" && echo "$tmp_dir"/$(basename "$file") else mktemp -p "$tmp_dir" fi } tac() { if [[ $(uname) == Darwin ]]; then tail -r else $(which tac) fi } mtime() { if [[ $(uname) == Darwin ]]; then stat -x "$1" | grep Modify | cut -d' ' -f2- else stat -c %y "$1" fi } # This function determines which http get tool the system has installed and returns an error if there isnt one getConfiguredClient() { if command -v curl &>/dev/null; then configuredClient="curl" elif command -v wget &>/dev/null; then configuredClient="wget" elif command -v http &>/dev/null; then configuredClient="httpie" else echo "Error: This tool requires either curl, wget, or httpie to be installed." >&2 return 1 fi } # Allows to call the users configured client without if statements everywhere # TODO return false if code is not 20x http_method() { local METHOD=$1; shift local header_opt; local header; local data_opt case "$configuredClient" in curl) [[ -n $token ]] && header_opt="--header" header="Authorization: token $token" [[ $METHOD =~ (POST|PATCH) ]] && data_opt='--data' curl -X "$METHOD" -A curl -s $header_opt "$header" $data_opt "@$http_data" "$@" ;; wget) [[ -n $token ]] && header_opt="--header" header="Authorization: token $token" [[ $METHOD =~ (POST|PATCH) ]] && data_opt='--body-file' wget --method="$METHOD" -qO- $header_opt "$header" $data_opt "$http_data" "$@" ;; httpie) [[ -n $token ]] && header="Authorization:token $token" [[ $METHOD =~ (POST|PATCH) ]] && data_opt="@$http_data" http -b "$METHOD" "$@" "$header" "$data_opt" ;; esac 2>&1 \ | tee $(tmp_file) \ || { echo "Error: no active internet connection" >&2; return 1; } } httpGet() { http_method GET "$@" } # Parse JSON from STDIN with string of python commands _process_json() { PYTHONIOENCODING=utf-8 \ python -c "from __future__ import print_function; import sys, json; $1" return "$?" } update() { # Author: Alexander Epstein https://github.com/alexanderepstein # Update utility version 2.2.0 # To test the tool enter in the defualt values that are in the examples for each variable repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then echo "Error: update utility has not been configured correctly." >&2 exit 1 elif [[ $latestVersion == "" ]]; then echo "Error: no active internet connection" >&2 exit 1 else if [[ $latestVersion != "$currentVersion" ]]; then echo "Version $latestVersion available" echo -n "Do you wish to update $repositoryName [Y/n]: " read -r answer if [[ $answer == [Yy] ]]; then cd ~ || { echo 'Update Failed'; exit 1; } if [[ -d ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi echo -n "Downloading latest version of: $repositoryName." # shellcheck disable=SC2015 git clone -q "https://github.com/$githubUserName/$repositoryName" && touch .BSnippetsHiddenFile || { echo "Failure!"; exit 1; } & while [ ! -f .BSnippetsHiddenFile ]; do { echo -n "."; sleep 2; };done rm -f .BSnippetsHiddenFile echo "Success!" cd $repositoryName || { echo 'Update Failed'; exit 1; } git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit." chmod a+x install.sh #this might be necessary in your case but wasnt in mine. ./$nameOfInstallFile "update" || exit 1 cd .. rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; } else exit 1 fi else echo "$repositoryName is already the latest version" fi fi } # Handle configuration cases _configure() { [[ $# == 0 ]] && (${EDITOR:-vi} "$CONFIG") && return 0 local valid_keys='user|token|folder|auto_sync|EDITOR|action|protocol|show_untagged' local key=$1; local value="$2" [[ ! $key =~ ^($valid_keys)$ ]] \ && echo "Not a valid key for configuration, use <$valid_keys> instead." \ && return 1 case $key in user) [[ -z $value ]] && echo 'Must specify username' >&2 && return 1 ;; token) [[ -n $value && ${#value} -ne 40 && ! $value =~ ^(\$|\`) ]] && echo 'Invalid token format, it is not 40 chars' >&2 && return 1 ;; auto_sync | show_untagged) [[ ! $value =~ ^(true|false)$ ]] && echo "$key must be either true or false" >&2 && return 1 ;; protocol) [[ ! $value =~ ^(https|ssh)$ ]] && echo 'protocol must be either https or ssh' >&2 && return 1 ;; action) value="'$2'" esac umask 0077 && touch "$CONFIG" local target=$key="$value" sed -i'' -e "/^$key=/ d" "$CONFIG" && [[ -n $target ]] && echo "$target" >> "$CONFIG" cat "$CONFIG" } # Prompt for username _ask_username() { while [[ ! $user =~ ^[[:alnum:]]+$ ]]; do [[ -n $user ]] && echo "Invalid username" read -r -p "Github username: " user < /dev/tty done _configure user "$user" } # Prompt for token # TODO check token scope contains gist, ref: https://developer.github.com/v3/apps/oauth_applications/#check-a-token _ask_token() { echo -n "Create a new token from web browser? [Y/n] " read -r answer < /dev/tty if [[ ! $answer =~ ^(N|n|No|NO|no)$ ]]; then python -mwebbrowser https://github.com/settings/tokens/new?scopes=gist fi while [[ ! $token =~ ^[[:alnum:]]{40}$ ]]; do [[ -n $token ]] && echo "Invalid token" read -r -p "Paste your token here (Ctrl-C to skip): " token < /dev/tty done _configure token "$token" } # Check configuration is fine with user setting _validate_config() { # shellcheck source=/dev/null source "$CONFIG" 2> /dev/null [[ $1 =~ ^(c|config|h|help|u|user|update|version) ]] && return 0 if [[ -z $user ]]; then echo 'Hi fellow! To access your gists, I need your Github username' echo "Also a personal token with scope which allows \"gist\"!" echo _ask_username && _ask_token && init=true elif [[ -z $token && $1 =~ ^(n|new|e|edit|D|delete)$ ]]; then _ask_token && return 0 echo 'To create/edit/delete a gist, a token is needed' && return 1 elif [[ -z $token && $1 =~ ^(f|fetch)$ && $2 =~ ^(s|star)$ ]]; then _ask_token && return 0 echo 'To get user starred gists, a token is needed' && return 1 fi } # Load configuration _apply_config() { _validate_config "$@" || return 1 [[ -z $folder || ! -w $(dirname "$folder") ]] && folder=~/gist; mkdir -p $folder INDEX=$folder/index; [[ -e $INDEX ]] || touch $INDEX getConfiguredClient } # extract trailing hashtags from description _trailing_hashtags() { grep -Eo " #[$TAG_CHAR #]+$" <<<"$1" | sed -Ee "s/.* [$TAG_CHAR]+//g" } _color_pinned_tags() { local pinned_tags=( $pin ) pattern='('$(sed -E 's/ /[[:space:]]|/g; s/\./[^ ]/g; s/$/[[:space:]]/' <<<"${pinned_tags[@]/#/#}")')' sed -E -e "s/$pattern/\\\e[33m\1\\\e[0m/g" <<<"$1 " } _color_description_title() { sed -E -e 's/^\[(.+)\]/\\e[33m[\1]\\e[0m/' <<<"$1" } # Return git status of a given repo _check_repo_status() { if [[ ! -d $1 ]]; then if [[ $auto_sync == 'true' ]]; then echo "\e[32m[cloning]\e[0m"; else echo "\e[32m[Not cloned yet]\e[0m"; fi else cd "$1" || exit 1 # git status is not clean or working on non-master branch if [[ -n $(git status --short) || $(cat .git/HEAD) != 'ref: refs/heads/master' ]] &>/dev/null; then echo "\e[36m[working]\e[0m" else # files contents are not the same with the last time called GIST API, so warn user to call 'gist fetch' [[ $(_blob_code "$1") != "$2" ]] 2>/dev/null && local status="\e[31m[outdated]\e[0m" # current HEAD is newer than remote, warn user to call 'git push' [[ -n $(git cherry) ]] 2>/dev/null && local status="\e[31m[ahead]\e[0m" echo "$status" fi fi } # check given index is necessary to handle _index_pattern() { if [[ -z "$INPUT" ]]; then echo .+ else echo "($(echo "$INPUT" | sed -Ee '/^ {4,}/ d; s/^ *//; /^$/ q' | cut -d' ' -f1 | xargs | tr ' ' '|'))" fi } _show_hint() { if [[ $display == 'tag' && -n $pin ]]; then local pinned_tags=( $pin ) echo > /dev/tty echo Pinned tags: "${pinned_tags[*]/#/#} " > /dev/tty elif [[ $hint != 'false' ]]; then local mtime="$(mtime $INDEX | cut -d'.' -f1)" echo > /dev/tty echo "Last updated at $mtime" > /dev/tty echo "Run \"$NAME fetch\" to keep gists up to date, or \"$NAME help\" for more details" > /dev/tty fi } # Display the list of gist, show username for starred gist # If hint=false, do not print hint to tty. If mark=, filter index with regex # If display=tag/language, print tags/languages instead or url _show_list() { if [[ ! -s $INDEX ]]; then echo "Index file is empty, please run commands ""$NAME" fetch" or ""$NAME" create"" return 0 fi sed -Ee "/^$mark/ !d; /^$(_index_pattern) / !d" $INDEX \ | while read -r "${INDEX_FORMAT[@]}"; do local message=$url if [[ $display == 'tag' ]]; then local tags=( ${tags_string//,/ } ); message="${tags[@]}" [[ $show_untagged == 'false' && ${#tags[@]} == '0' ]] && continue local width=45; local align=' '; elif [[ $display == 'language' ]]; then message="$(tr ',' '\n' <<< "$file_array" | sed -Ee 's/.+@/#/' | uniq | xargs)" local width=45; local align=' '; fi local extra="$(printf "%-4s" "$file_num $comment_num")" local status=''; status=$(_check_repo_status "$folder/${url##*/}" "$blob_code") [[ $index =~ ^s ]] && description="$(printf "%-12s" ["${author}"]) ${description}" raw_output="$(printf "%-3s" "$index") $(printf "%${align:--}${width:-56}s" "$message") $extra ${status:+${status} }$(_color_description_title "$description")" [[ -n $pin ]] && raw_output="$(_color_pinned_tags "$raw_output")" decorator=$(( $(grep -o '\\e\[0m' <<<"$raw_output" | wc -l) *9 )) echo -e "$raw_output" | cut -c -$(( $(tput cols) +decorator )) done [[ -z $INPUT ]] && _show_hint || true } # Grep description, filename or file content with a given pattern # TODO add option to configure case-sensitive _grep_content() { if [[ -z $1 ]]; then echo 'Please give a pattern' && return 1; fi sed -Ee "/^$(_index_pattern) / !d" $INDEX \ | while read -r "${INDEX_FORMAT[@]}"; do # grep from description if grep --color=always -iq "$1" <<<"$description"; then hint=false mark="$index " _show_list else local repo=$folder/${url##*/} [[ -d $repo ]] && cd "$repo" || continue # grep from filenames local file=$(ls "$repo" | grep --color=always -Ei "$1") # grep from content of files # Abort error message to prevent weird file name, for example: https://gist.github.com/6057f4a3a533f7992c60 local content=$(grep --color=always -EHi -m1 "$1" * 2>/dev/null | head -1) [[ -n $file && file="$file\n" || -n $content ]] \ && hint=false mark="$index " _show_list \ && echo -e " $file$content" fi done } # Parse JSON object of the result of gist fetch _parse_gists() { _process_json ' raw = json.load(sys.stdin) for gist in raw: print(gist["html_url"], end=" ") print(gist["public"], end=" ") print(",".join(file["raw_url"] for file in gist["files"].values()), end=" ") print(",".join(file["filename"].replace(" ", "-") + "@" + str(file["language"]).replace(" ", "-") for file in gist["files"].values()), end=" ") print(len(gist["files"]), end=" ") print(gist["comments"], end=" ") print(gist["owner"]["login"], end=" ") print(gist["created_at"], end=" ") print(gist["updated_at"], end=" ") print(gist["description"]) ' } # Parse response from 'gist fetch' to the format for index file _parse_response() { _parse_gists \ | tac | nl -s' ' \ | while read -r "${INDEX_FORMAT[@]:0:2}" public file_url_array "${INDEX_FORMAT[@]:4:7}"; do local private_prefix=''; [[ $public == 'False' ]] && private_prefix=p [[ -n $1 ]] && local index=${1}; index=${private_prefix}${prefix}${index} local blob_code=$(echo "$file_url_array" | tr ',' '\n' | sed -E -e 's#.*raw/(.*)/.*#\1#' | sort | cut -c -7 | paste -s -d '-' -) file_array=${file_array//@None/@Text} local hashtags_suffix="$(_trailing_hashtags "$description")" description="${description%"$hashtags_suffix"}" local hashtags="$(echo "$hashtags_suffix" | xargs)" local tags_string="${hashtags// /,}"; [[ -z $tags_string ]] && tags_string=',' eval echo "${INDEX_FORMAT[@]/#/$}" done } # Get latest list of gists from Github API # TODO pagnation for more than 100 gists _fetch_gists() { echo "fetching $user's gists from $GITHUB_API..." echo local route="users/$user/gists" local prifix='' if [[ $mark == s ]]; then route='gists/starred' prefix=s fi result=$(http_method GET $GITHUB_API/$route?per_page=100 | prefix=$prefix _parse_response) [[ -z $result ]] && echo 'Not a single valid gist' && return 0 sed -i'' -Ee "/^$mark/ d" $INDEX && echo "$result" >> $INDEX hint=$hint _show_list [[ $auto_sync == 'true' ]] && (_sync_repos &> /dev/null &) true } # Fetch gists for a given user # TODO pagnation for more than 100 gists _query_user() { local route="users/$1/gists" result="$(http_method GET $GITHUB_API/"$route"?per_page=100 | _parse_response)" [[ -z $result ]] && echo "Failed to query $1's gists" && return 1 echo "$result" \ | while read -r "${INDEX_FORMAT[@]}"; do echo "$url $author $file_num $comment_num $description" | cut -c -"$(tput cols)" done } # Return the unique code for current commit, to compare repo status and the result of 'gist fetch' # Because there is no way to get commit SHA with 'gist fetch' _blob_code() { cd "$1" && git ls-tree master | cut -d' ' -f3 | cut -c-7 | sort | paste -sd '-' } _pull_if_needed() { sed -ne "/$1 / p" "$INDEX" \ | while read -r "${INDEX_FORMAT[@]}"; do local repo; repo=$folder/$1 local blob_code_local; blob_code_local=$(_blob_code "$repo") cd "$repo" \ && [[ $blob_code_local != "$blob_code" ]] \ && [[ $(git rev-parse origin/master) == $(git rev-parse master) ]] \ && git pull & done } # Update local git repos _sync_repos() { comm -1 <(ls -A "$folder" | sort) \ <(cut -d' ' -f1-2 < "$INDEX" | sed -ne "/^$mark/ s#.*/##p" | sort) \ | { result=$(cat) # clone repos which are not in the local sed -ne '/^\t/ !p' <<<"$result" \ | xargs -I{} --max-procs 8 git clone "$(_repo_url {})" $folder/{} & # if repo is cloned, do 'git pull' if remote repo has different blob objects sed -ne '/^\t/ s/\t//p' <<<"$result" \ | while read GIST_ID; do _pull_if_needed "$GIST_ID" done } } # Get the url where to clone repo, take user and repo name as parameters _repo_url() { if [[ $protocol == 'ssh' ]]; then echo "git@gist.github.com:$1.git" else echo "https://gist.github.com/$1.git" fi } # Get gist id from index files _gist_id() { GIST_ID=$(sed -En -e "/^$1 / s#^$1 [^ ]+/([[:alnum:]]+) .+#\1#p" $INDEX | head -1) if [[ -z $GIST_ID || ! $1 =~ [0-9a-z]+ ]]; then echo -e "$(hint=false _show_list | sed -Ee 's/^( *[0-9a-z]+)/\\e[5m\1\\e[0m/')" echo echo -e "Invalid index: \e[33m$1\e[0m" echo 'Use the indices blinking instead (like 1 or s1)' return 1 fi } # set gist id either by given index or current directory _set_gist_id() { if [[ -z $1 ]]; then [[ $(dirname $(pwd)) == $folder ]] && GIST_ID=$(basename $(pwd)) && return 0 fi _gist_id "$1" || return 1 } # Show path of repo by gist ID, and perform action _goto_gist() { echo "$folder/$GIST_ID" touch "$folder/$GIST_ID" if [[ $* =~ (-n|--no-action) ]]; then return 0 elif [[ -z $action ]]; then action='echo Inside subshell, press \ to exit; ${SHELL:-bash}' fi cd "$folder/$GIST_ID" && eval "$action" } # Return the path of local repo with a given index _goto_gist_by_index() { _gist_id "$1" || return 1 if [[ ! -d $folder/$GIST_ID ]]; then echo 'Cloning gist as repo...' if git clone "$(_repo_url "$GIST_ID")" "$folder/$GIST_ID"; then echo 'Repo is cloned' > /dev/tty else echo 'Failed to clone the gist' > /dev/tty return 1 fi fi _goto_gist "$@" } # Delete gists with given indices # Specify --force to suppress confirmation _delete_gist() { if [[ ! $* =~ '--force' ]]; then read -r -p "Delete gists above? [y/N] " response response=${response,,} [[ ! $response =~ ^(yes|y)$ ]] && return 0 fi for i in "$@"; do _gist_id "$i" &> /dev/null || continue http_method DELETE "$GITHUB_API/gists/$GIST_ID" \ && echo "$i" deleted \ && sed -E -i'' -e "/^$i / d" $INDEX done } # Remove repos which are not in index file anymore _clean_repos() { comm -23 <(find $folder -maxdepth 1 -type d | sed -e '1d; s#.*/##' | sort) \ <(cut -d' ' -f2 < "$INDEX" | sed -e 's#.*/##' | sort 2> /dev/null ) \ | while read -r dir; do mv $folder/"$dir" /tmp && echo $folder/"$dir" is moved to /tmp done } # Parse JSON object of gist user comments _parse_comment() { _process_json ' raw = json.load(sys.stdin); for comment in raw: print() print("|", "user:", comment["user"]["login"]) print("|", "created_at:", comment["created_at"]) print("|", "updated_at:", comment["updated_at"]) print("|", comment["body"]) ' } # Show the detail of a gist # TODO add parameter --comment to fetch comments _show_detail() { _set_gist_id "$1" || return 1 sed -En -e "/[^ ]+ [^ ]+$GIST_ID / p" $INDEX \ | while read -r "${INDEX_FORMAT[@]}"; do echo -e desc: $(_color_description_title "$description") echo -e tags: ${tags_string//,/ } echo -e site: https://gist.github.com/"$GIST_ID" echo -e API : https://api.github.com/gists/"$GIST_ID" echo -e created_at: "$created_at" echo -e updated_at: "$updated_at" echo -e files: tr ',' '\n' <<<"${file_array//@/ }" | column -t | sed -e 's/^/ /' done } # Open Github repository import page _export_to_github() { _gist_id "$1" || return 1 echo Put the folowing URL into web page: echo -n "https://gist.github.com/$GIST_ID.git" python -mwebbrowser https://github.com/new/import } # Simply commit current changes and push to remote _push_to_remote() { if [[ ! $(pwd) =~ ^$folder/[0-9a-z]+$ ]]; then _gist_id "$1" || return 1 cd "$folder/$GIST_ID" || exit fi if [[ -n $(git status --short) ]]; then git add . && git commit -m 'update' fi if [[ -n $(git cherry) ]]; then git push origin master && (hint=false _fetch_gists &> /dev/null &) fi } # Set filename/description/permission for a new gist _set_gist() { files=() description=''; filename=''; public=True while [[ -n "$*" ]]; do case $1 in -d | --desc) description="$2" shift; shift;; -f | --file) filename="$2" shift; shift;; -p) public=False shift;; *) files+=($1) shift;; esac done ls "${files[@]}" > /dev/null || return 1 } # Let user type the content of gist before setting filename _new_file() { tmp_file=$(tmp_file) if [[ -z $INPUT ]]; then echo "Type a gist. to cancel, when done" > /dev/tty cat > "$tmp_file" else echo "$INPUT" > "$tmp_file" fi echo > /dev/tty [[ -z $1 ]] && read -e -r -p 'Type file name: ' filename < /dev/tty mv "$tmp_file" "$tmp_dir"/"$filename" echo "$tmp_dir"/"$filename" } # Parse JSON object of a single gist _gist_body() { _process_json " import os.path files_json = {} files = sys.stdin.readline().split() description = sys.stdin.readline().replace('\n','') for file in files: with open(file, 'r') as f: files_json[os.path.basename(file)] = {'content': f.read()} print(json.dumps({'public': $public, 'files': files_json, 'description': description})) " } # Create a new gist with files. If success, also update index file and clone the repo _create_gist() { _set_gist "$@" || return 1 [[ -z ${files[*]} ]] && files+=($(_new_file "$filename")) [[ -z $description ]] && read -e -r -p 'Type description: ' description < /dev/tty echo 'Creating a new gist...' http_data=$(tmp_file) echo -e "${files[*]}\n$description" \ | _gist_body > "$http_data" \ && http_method POST $GITHUB_API/gists \ | xargs -I{} -0 echo "[{}]" \ | _parse_response $(( $(sed -e '/^s/ d' $INDEX | wc -l) +1 )) \ | tee -a $INDEX \ | cut -d' ' -f2 | sed -E -e 's#.*/##' \ | (xargs -I{} git clone "$(_repo_url {})" $folder/{} &> /dev/null &) # shellcheck disable=2181 if [[ $? -eq 0 ]]; then echo 'Gist is created' INPUT=$(tail -1 $INDEX | cut -d' ' -f1) hint=false _show_list | tail -1 else echo 'Failed to create gist' fi } # Update description of a gist _edit_gist() { local index=$1; shift _gist_id "$index" || return 1 if [[ -z "$@" ]]; then read -r "${INDEX_FORMAT[@]}" <<<"$(sed -ne "/^$index / p" $INDEX)" read -e -p 'Edit description: ' -i "$description" -r DESC < /dev/tty tags=( ${tags_string//,/ } ) DESC="$DESC ${tags[*]}" else DESC="$@" fi http_data=$(tmp_file) echo '{' \"description\": \""${DESC//\"/\\\"}"\" '}' > "$http_data" new_record=$(http_method PATCH "$GITHUB_API/gists/$GIST_ID" \ | sed -e '1 s/^/[/; $ s/$/]/' \ | _parse_response "${index#[[:alpha:]]}" ) [[ -n $new_record ]] && sed -i'' -E -e "/^$index / s^.+^$new_record^" $INDEX \ && hint=false mark="$index " _show_list \ || echo 'Fail to modify gist description' } # Print helper message usage() { sed -Ene "/^#/ !q; 1,/^# --/ d; s/^# //p; s/^( *|Usage: )gist/\1$NAME/" "$0" } # Check remote urls of all repos match current protocol in configuration file # If not, update them _check_protocol() { find $folder -maxdepth 1 -mindepth 1 -type d \ | while read -r repo; do cd "$repo" || exit 1 url=$(git remote get-url origin) if [[ $protocol == 'ssh' && $url =~ ^https ]]; then git remote set-url origin "git@gist.github.com:$(basename $(pwd)).git" elif [[ $protocol == 'https' && $url =~ ^git ]]; then git remote set-url origin "https://gist.github.com/$(basename $(pwd)).git" fi done } _tag_gist() { # if no tag is given, show gist list with tags if [[ -z $* ]]; then display=tag _show_list # if user want to change tags of a gist elif _gist_id "$1" &>/dev/null; then _show_detail "$1" | sed 3,6d && echo read -r "${INDEX_FORMAT[@]}" <<<"$(sed -ne "/^$1 / p" $INDEX)" local tags="$(sed -e 's/,//g; s/#/ /g; s/^ //g' <<<"$tags_string")" read -e -p 'Edit tags: ' -i "$tags" -r -a new_tags < /dev/tty local hashtags=( $(sed -Ee 's/#+/#/g' <<<${new_tags[@]/#/#}) ) ($0 edit "$1" "${description}${hashtags:+ }${hashtags[@]}" &>/dev/null &) # if user want to filter gists with given tags else local pattern="($(sed -E 's/([^ ]+)/#\1/g; s/ /[[:space:]]|/g; s/\./[^ ]/g' <<<"$@") )" hint=false mark=${INPUT:+.} display=tag _show_list | grep --color=always -E "$pattern" fi } # show all tags and pinned tags _show_tags() { local pinned_tags=( $pin ) local tags=$(while read -r "${INDEX_FORMAT[@]}"; do echo ${tags_string//,/ } done < $INDEX | tr ' ' '\n' | sed -e '/^$/d' | sort -u) for prefix in {0..9} {a..z} {A-Z} [^0-9a-zA-Z]; do local line=$(echo "$tags" | grep -Eo "#$prefix[^ ]+" | tr '\n' ' ') [[ -z $line ]] && continue # add color to pinned tags echo -e "$(_color_pinned_tags "$line")" done echo if [[ ${#pinned_tags} == 0 ]]; then echo "Run \"$NAME pin ...\" to pin/unpin tags" else echo Pinned tags: "${pinned_tags[@]/#/#}" fi } # pin/unpin tags _pin_tags() { # if no arguments, print gists with pinned tags if [[ -z $* && -n $pin ]]; then hint=false _tag_gist "$pin" else local new_pinned=( $(echo "$pin" "$*" | tr ' ' '\n' | sort | uniq -u | xargs) ) for tag in "${new_pinned[@]}"; do if [[ $tag =~ [p]*[0-9]+ ]]; then echo Invalid tag: "$tag" return 1 fi done || exit 1 pin="${new_pinned[@]}" _show_tags sed -i'' -e "/^pin=/ d" "$CONFIG" && echo pin=\'"${new_pinned[*]}"\' >> "$CONFIG" fi } # show languages of files in gists _gists_with_languages() { local pattern="($(sed -E 's/([^ ]+)/#\1/g; s/ /|/g' <<<"$@"))" display=language _show_list | grep --color=always -Ei "$pattern" } _gists_with_range() { [[ ! $* =~ ^s?[0-9]*-s?[0-9]*$ ]] && echo 'Invalid range' && exit 1 local prefix=''; [[ $* =~ s ]] && prefix=s local maximum=$(sed -Ene "/^${prefix:-[^s]}/ p" $INDEX | wc -l) local range=$(sed -Ee "s/s//g; s/^-/1-/; s/-$/-$maximum/; s/-/ /" <<< "$*") INPUT=$(seq "$range" | sed -e "s/^/p?$prefix/") hint=false _show_list } _access_last_index() { GIST_ID=$(ls -tup $folder | grep / | head -1) _goto_gist "$@" } _apply_config "$@" || exit 1 if [[ $init ]]; then _fetch_gists; exit 0; fi case "$1" in "") _show_list ;; star | s) mark=s; _show_list ;; all | a) mark=.; _show_list ;; fetch | f) [[ $2 =~ ^(s|star)$ ]] && mark=s || mark=[^s] _fetch_gists ;; new | n) shift _create_gist "$@" ;; edit | e) shift _edit_gist "$@" ;; sync | S) _sync_repos ;; detail | d) shift _show_detail "$@" ;; delete | D) shift _delete_gist "$@" ;; clean | C) _clean_repos ;; config | c) shift _configure "$@" && (_apply_config config && _check_protocol) ;; user | u) shift _query_user "$@" ;; grep | g) shift _grep_content "$@" ;; github | G) shift _export_to_github "$1" ;; push | P) shift _push_to_remote "$1" ;; tag | t) shift _tag_gist "$@" ;; tags | tt) _show_tags ;; pin | p) shift _pin_tags "$@" ;; lan | l) shift _gists_with_languages "$@" ;; *-*) mark=.; _gists_with_range "$@" ;; last | L) _access_last_index "$@" ;; version) echo "Version $currentVersion" ;; update) update ;; help | h) usage ;; *) _goto_gist_by_index "$@" ;; esac ================================================ FILE: install.sh ================================================ #!/usr/bin/env bash # Author: Alexander Epstein https://github.com/alexanderepstein currentVersion="1.23.0" declare -a tools=(bak2dvd bash-snippets cheat cloudup crypt cryptocurrency currency geo gist lyrics meme movies newton pwned qrify short siteciphers stocks taste todo transfer weather ytview) declare -a extraLinuxTools=(maps) declare -a extraDarwinTools usedGithubInstallMethod="0" prefix="/usr/local" askInstall() { read -p "Do you wish to install $1 [Y/n]: " answer answer=${answer:-Y} if [[ "$answer" == [Yy] ]]; then cd "$1" || return 1 echo -n "Installing $1: " chmod a+x "$1" cp "$1" /usr/local/bin > /dev/null 2>&1 || { echo "Failure"; echo "Error copying file, try running install script as sudo"; exit 1; } echo "Success" cd .. || return 1 fi } updateTool() { if [[ -f /usr/local/bin/$1 ]]; then usedGithubInstallMethod="1" cd "$1" || return 1 echo -n "Installing $1: " chmod a+x "$1" cp "$1" /usr/local/bin > /dev/null 2>&1 || { echo "Failure"; echo "Error copying file, try running install script as sudo"; exit 1; } echo "Success" cd .. || return 1 fi } extraUpdateTool() { if [[ -f /usr/local/bin/$1 ]]; then usedGithubInstallMethod="1" cd extras || return 1 cd "$2" || return 1 cd "$1" || return 1 echo -n "Installing $1: " chmod a+x "$1" cp "$1" /usr/local/bin > /dev/null 2>&1 || { echo "Failure"; echo "Error copying file, try running install script as sudo"; exit 1; } echo "Success" cd .. || return 1 cd .. || return 1 cd .. || return 1 fi } singleInstall() { cd "$1" || exit 1 echo -n "Installing $1: " chmod a+x "$1" cp "$1" $prefix/bin > /dev/null 2>&1 || { echo "Failure"; echo "Error copying file, try running install script as sudo"; exit 1; } echo "Success" cd .. || exit 1 } copyManpage() { manPath="$prefix/share/man/man1" if [ -f "$prefix/man/man1/bash-snippets.1" ]; then rm -f "$prefix/man/man1/bash-snippets.1"; fi cp bash-snippets.1 $manPath 2>&1 || { echo "Failure"; echo "Error copying file, try running install script as sudo"; exit 1; } } response=$( echo "$@" | grep -Eo "\-\-prefix") if [[ $response == "--prefix" ]]; then prefix=$(echo -n "$@" | sed -e 's/--prefix=\(.*\) .*/\1/' | cut -d " " -f 1) mkdir -p "$prefix"/bin "$prefix"/share/man/man1 if [[ $2 == "all" ]];then for tool in "${tools[@]}"; do singleInstall "$tool" || exit 1 done else for tool in "${@:2}"; do singleInstall "$tool" || exit 1 done fi copyManpage || exit 1 elif [[ $# == 0 ]]; then for tool in "${tools[@]}"; do askInstall "$tool" || exit 1 done copyManpage || exit 1 elif [[ $1 == "update" ]]; then echo "Updating scripts..." for tool in "${tools[@]}"; do updateTool "$tool" || exit 1 done if [[ $(uname -s) == "Linux" ]]; then for tool in "${extraLinuxTools[@]}"; do extraUpdateTool "$tool" Linux || exit 1 done fi if [[ $(uname) == "Darwin" ]];then for tool in "${extraDarwinTools[@]}"; do extraUpdateTool "$tool" Darwin || exit 1 done fi if [[ $usedGithubInstallMethod == "1" ]]; then copyManpage || exit 1 else echo "It appears you have installed bash-snippets through a package manager, you must update it with the respective package manager." exit 1 fi elif [[ $1 == "all" ]]; then for tool in "${tools[@]}"; do singleInstall "$tool" || exit 1 done copyManpage || exit 1 else singleInstall "$1" || exit 1 copyManpage || exit 1 fi echo -n "( •_•)" sleep .75 echo -n -e "\r( •_•)>⌐■-■" sleep .75 echo -n -e "\r " echo -e "\r(⌐■_■)" sleep .5 echo "Bash Snippets version $currentVersion" echo "https://github.com/alexanderepstein/Bash-Snippets" ================================================ FILE: lyrics/lyrics ================================================ #!/usr/bin/env bash # Author: Alexander Epstein https://github.com/alexanderepstein currentVersion="1.23.0" configuredClient="" artist="false" song="false" filePath="" ## This function determines which http get tool the system has installed and returns an error if there isnt one getConfiguredClient() { if command -v curl &>/dev/null; then configuredClient="curl" elif command -v wget &>/dev/null; then configuredClient="wget" elif command -v http &>/dev/null; then configuredClient="httpie" elif command -v fetch &>/dev/null; then configuredClient="fetch" else echo "Error: This tool requires either curl, wget, httpie or fetch to be installed." >&2 return 1 fi } getConfiguredPython() { if command -v python3 &>/dev/null; then configuredPython="python3" elif command -v python2 &>/dev/null; then configuredPython="python2" elif command -v python &>/dev/null; then configuredPython="python" else echo "Error: This tool requires python to be installed." return 1 fi } if [[ $(uname) != "Darwin" ]]; then python() { case "$configuredPython" in python3) python3 "$@" ;; python2) python2 "$@" ;; python) python "$@" ;; esac } fi ## Grabs an element from a a json string and then echoes it to stdout ## $1 = the JSON string ## $n+1 = the elements to be indexed AccessJsonElement() { json="$1" shift accessor="" for element in "$@"; do accessor="${accessor}['$element']" done echo "$json" | python -c "from __future__ import print_function; import sys, json; print(json.load(sys.stdin)${accessor})" 2> /dev/null return "$?" } ## Allows to call the users configured client without if statements everywhere httpGet() { case "$configuredClient" in curl) curl -A curl -s "$@" ;; wget) wget -qO- "$@" ;; httpie) http -b GET "$@" ;; fetch) fetch -q "$@" ;; esac } update() { # Author: Alexander Epstein https://github.com/alexanderepstein # Update utility version 1.2.0 # To test the tool enter in the defualt values that are in the examples for each variable repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then echo "Error: update utility has not been configured correctly." >&2 exit 1 elif [[ $latestVersion == "" ]]; then echo "Error: no active internet connection" >&2 exit 1 else if [[ "$latestVersion" != "$currentVersion" ]]; then echo "Version $latestVersion available" echo -n "Do you wish to update $repositoryName [Y/n]: " read -r answer if [[ "$answer" == [Yy] ]]; then cd ~ || { echo 'Update Failed'; exit 1; } if [[ -d ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi git clone "https://github.com/$githubUserName/$repositoryName" || { echo "Couldn't download latest version"; exit 1; } cd $repositoryName || { echo 'Update Failed'; exit 1; } git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit." chmod a+x install.sh #this might be necessary in your case but wasnt in mine. ./$nameOfInstallFile "update" || exit 1 cd .. rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; } else exit 1 fi else echo "$repositoryName is already the latest version" fi fi } checkInternet() { httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request } getLyrics() { encodedArtist=$(echo "$1" | sed s/" "/%20/g | sed s/"&"/%26/g | sed s/,/%2C/g | sed s/-/%2D/g) encodedSong=$(echo "$2" | sed s/" "/%20/g | sed s/"&"/%26/g | sed s/,/%2C/g | sed s/-/%2D/g) response=$(httpGet "https://api.lyrics.ovh/v1/$encodedArtist/$encodedSong") lyrics="$(AccessJsonElement "$response" "lyrics" 2> /dev/null)" if [[ $lyrics == "" ]];then { echo "Error: no lyrics found!"; return 1; }; fi } printLyrics() { if [[ $filePath == "" ]];then echo -e "$lyrics" else if [ -f "$filePath" ];then echo -n "File already exists, do you want to overwrite it [Y/n]: " read -r answer if [[ "$answer" == [Yy] ]]; then echo -e "$lyrics" > "$filePath"; fi else echo -e "$lyrics" > "$filePath"; fi fi } usage() { cat <&2 exit 1 ;; h) usage exit 0 ;; v) echo "Version $currentVersion" exit 0 ;; u) getConfiguredClient || exit 1 checkInternet || exit 1 update exit 0 ;; f) filePath="$OPTARG" ;; a) artist="true" if [[ "$(echo "$@" | grep -Eo "\-s")" == "-s" ]];then song="true";fi # wont go through both options if arg spaced and not quoted this solves that issue (dont need this but once had bug on system where it was necessary) if [[ "$(echo "$@" | grep -Eo "\-f")" == "-f" ]];then filePath=$(echo "$@" | grep -Eo "\-f [ a-z A-Z / 0-9 . \ ]*[ -]?" | sed s/-f//g | sed s/-//g | sed s/^" "//g);fi ;; s) song="true" if [[ "$(echo "$@" | grep -Eo "\-a")" == "-a" ]];then artist="true";fi # wont go through both options if arg spaced and not quoted this solves that issue (dont need this but once had bug on system where it was necessary) if [[ "$(echo "$@" | grep -Eo "\-f")" == "-f" ]];then filePath=$(echo "$@" | grep -Eo "\-f [ a-z A-Z / 0-9 . \ ]*[ -]?" | sed s/-f//g | sed s/-//g | sed s/^" "//g);fi ;; :) echo "Option -$OPTARG requires an argument." >&2 exit 1 ;; esac done # special set of first arguments that have a specific behavior across tools if [[ $# == "0" ]]; then usage ## if calling the tool with no flags and args chances are you want to return usage exit 0 elif [[ $# == "1" ]]; then if [[ $1 == "update" ]]; then getConfiguredClient || exit 1 checkInternet || exit 1 update || exit 1 exit 0 elif [[ $1 == "help" ]]; then usage exit 0 fi fi if ($artist && ! $song) || ($song && ! $artist);then echo "Error: the -a and the -s flag must be used to fetch lyrics." exit 1 elif $artist && $song;then song=$(echo "$@" | grep -Eo "\-s [ a-z A-Z 0-9 . \ ]*[ -]?" | sed s/-s//g | sed s/-//g | sed s/^" "//g) if [[ $song == "" ]];then { echo "Error: song could not be parsed from input."; exit 1; };fi artist=$(echo "$@" | grep -Eo "\-a [ a-z A-Z 0-9 . \ ]*[ -]?" | sed s/-a//g | sed s/-//g | sed s/^" "//g) if [[ $artist == "" ]];then { echo "Error: artist could not be parsed from input."; exit 1; };fi getConfiguredClient || exit 1 if [[ $(uname) != "Darwin" ]]; then getConfiguredPython || exit 1;fi checkInternet || exit 1 getLyrics "$artist" "$song" || exit 1 printLyrics else { clear; echo "You shouldnt be here but maaaaaaybeee you slipped passed me, learn to use the tool!"; sleep 5; clear;} usage exit 1 fi ================================================ FILE: meme/meme ================================================ #!/usr/bin/env bash # Author: Navan Chauhan https://github.com/navanchauhan currentVersion="1.23.0" configuredClient="" fileName="" ## This function determines which http get tool the system has installed and returns an error if there isnt one getConfiguredClient() { if command -v curl &>/dev/null; then configuredClient="curl" elif command -v wget &>/dev/null; then configuredClient="wget" elif command -v http &>/dev/null; then configuredClient="httpie" elif command -v fetch &>/dev/null; then configuredClient="fetch" else echo "Error: This tool requires either curl, wget, httpie or fetch to be installed." >&2 return 1 fi } ## Allows to call the users configured client without if statements everywhere httpGet() { case "$configuredClient" in curl) curl -A curl -Ls "$@" ;; wget) wget -qO- "$@" ;; httpie) http -b GET "$@" ;; fetch) fetch -q "$@" ;; esac } update() { # Author: Alexander Epstein https://github.com/alexanderepstein # Update utility version 1.2.0 # To test the tool enter in the defualt values that are in the examples for each variable repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then echo "Error: update utility has not been configured correctly." >&2 exit 1 elif [[ $latestVersion == "" ]]; then echo "Error: no active internet connection" >&2 exit 1 else if [[ "$latestVersion" != "$currentVersion" ]]; then echo "Version $latestVersion available" echo -n "Do you wish to update $repositoryName [Y/n]: " read -r answer if [[ "$answer" == [Yy] ]]; then cd ~ || { echo 'Update Failed'; exit 1; } if [[ -d ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi git clone "https://github.com/$githubUserName/$repositoryName" || { echo "Couldn't download latest version"; exit 1; } cd $repositoryName || { echo 'Update Failed'; exit 1; } git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit." chmod a+x install.sh #this might be necessary in your case but wasnt in mine. ./$nameOfInstallFile "update" || exit 1 cd .. rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; } else exit 1 fi else echo "$repositoryName is already the latest version" fi fi } checkInternet() { httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request } main(){ echo -n "Enter the name for the meme's background (Ex. buzz, doge, blb ): " read bg echo -n "Enter the text for the first line: " read raw_first almost_first=$(echo "$raw_first" | awk '{print tolower($0)}') first=$(echo "$almost_first" | sed -e 's/ /_/g') echo -n "Enter the text for the second line: " read raw_second almost_second=$(echo "$raw_second" | awk '{print tolower($0)}') second=$(echo "$almost_second" | sed -e 's/ /_/g') if [ -z "$first" ] then first=$(echo "_") else echo "" fi if [ -z "$second" ] then second=$(echo "_") else echo "" fi httpGet "https://memegen.link/$bg/$first/$second.jpg" >> "$fileName".png || return 1 return 0 } usage() { cat <&2 exit 1 ;; h) usage exit 0 ;; v) echo "Version $currentVersion" exit 0 ;; u) getConfiguredClient || exit 1 checkInternet || exit 1 update exit 0 ;; f) fileName=$OPTARG getConfiguredClient || exit 1 checkInternet || exit 1 main || exit 1 exit 0 ;; :) echo "Option -$OPTARG requires an argument." >&2 exit 1 ;; esac done # special set of first arguments that have a specific behavior across tools if [[ $# == "0" ]]; then getConfiguredClient || exit 1 checkInternet || exit 1 if [[ $fileName == "" ]]; then fileName="meme" fi main || exit 1 exit 0 elif [[ $# == "1" ]]; then if [[ $1 == "update" ]]; then getConfiguredClient || exit 1 checkInternet || exit 1 update || exit 1 exit 0 elif [[ $1 == "help" ]]; then usage exit 0 fi fi ================================================ FILE: movies/movies ================================================ #!/usr/bin/env bash # Author: Alexander Epstein https://github.com/alexanderepstein currentVersion="1.23.0" configuredClient="" configuredPython="" detail=false ## This function determines which http get tool the system has installed and returns an error if there isnt one getConfiguredClient() { if command -v curl &>/dev/null; then configuredClient="curl" elif command -v wget &>/dev/null; then configuredClient="wget" elif command -v http &>/dev/null; then configuredClient="httpie" elif command -v fetch &>/dev/null; then configuredClient="fetch" else echo "Error: This tool requires either curl, wget, httpie or fetch to be installed." >&2 return 1 fi } ## Allows to call the users configured client without if statements everywhere httpGet() { case "$configuredClient" in curl) curl -A curl -s "$@" ;; wget) wget -qO- "$@" ;; httpie) http -b GET "$@" ;; fetch) fetch -q "$@" ;; esac } getConfiguredPython() { if command -v python3 &>/dev/null; then configuredPython="python3" elif command -v python2 &>/dev/null; then configuredPython="python2" elif command -v python &>/dev/null; then configuredPython="python" else echo "Error: This tool requires python to be installed." return 1 fi } if [[ $(uname) != "Darwin" ]]; then python() { case "$configuredPython" in python3) python3 "$@" ;; python2) python2 "$@" ;; python) python "$@" ;; esac } fi ## Grabs an element from a a json string and then echoes it to stdout ## $1 = the JSON string ## $n+1 = the elements to be indexed AccessJsonElement() { json="$1" shift accessor="" for element in "$@"; do accessor="${accessor}['$element']" done echo "$json" | python -c "from __future__ import print_function; import sys, json; print(json.load(sys.stdin)${accessor})" 2> /dev/null return "$?" } checkInternet() { httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request } ## This function grabs information about a movie and using python parses the ## JSON response to extrapolate the information for storage getMovieInfo() { apiKey=e3aeac39 # try not to abuse this it is a key that came from the ruby-scripts repo I link to. movie=$( (echo "$@" | tr " " + ) | sed 's/-d+//g' ) ## format the inputs to use for the api. Added sed command to filter -d flag. export PYTHONIOENCODING=utf8 #necessary for python in some cases movieInfo=$(httpGet "http://www.omdbapi.com/?t=$movie&apikey=$apiKey") > /dev/null # query the server and get the JSON response ## check to see if the movie was found checkResponse=$(echo "$movieInfo" | python -c "from __future__ import print_function; import sys, json; print(json.load(sys.stdin)['Response'])" 2> /dev/null) if [[ $checkResponse == "False" ]]; then echo "$movieInfo" | python -c "from __future__ import print_function; import sys, json; print(json.load(sys.stdin)['Error'])" 2> /dev/null return 1 fi # The rest of the code is just extrapolating the data with python from the JSON response title="$(AccessJsonElement "$movieInfo" "Title")" year="$(AccessJsonElement "$movieInfo" "Year")" runtime="$(AccessJsonElement "$movieInfo" "Runtime")" imdbScore=$(echo "$movieInfo" | python -c "from __future__ import print_function; import sys, json; print(json.load(sys.stdin)['Ratings'][0]['Value'])" 2> /dev/null) tomatoScore=$(echo "$movieInfo" | python -c "from __future__ import print_function; import sys, json; print(json.load(sys.stdin)['Ratings'][1]['Value'])" 2> /dev/null) rated="$(AccessJsonElement "$movieInfo" "Rated")" genre="$(AccessJsonElement "$movieInfo" "Genre")" director="$(AccessJsonElement "$movieInfo" "Director")" actors="$(AccessJsonElement "$movieInfo" "Actors")" plot="$(AccessJsonElement "$movieInfo" "Plot")" if $detail; then awards="$(AccessJsonElement "$movieInfo" "Awards")" boxOffice="$(AccessJsonElement "$movieInfo" "BoxOffice")" metacriticScore=$(echo "$movieInfo" | python -c "from __future__ import print_function; import sys, json; print(json.load(sys.stdin)['Ratings'][2]['Value'])" 2> /dev/null) production="$(AccessJsonElement "$movieInfo" "Production")" fi } # Print key: value info printKV() { key=$1 val=$2 ROW="|%11s: %-40s|\n" WIDTH=53 # If value too long (greater then 43 char), split it into several line if [[ ${#val} -le $((WIDTH - 10)) ]]; then printf "$ROW" "$key" "$val" else printf "$ROW" "$key" printf "%s\n" "$val" | fmt -w 50 \ | while IFS= read -r line; do printf "| %-50s |\n" "$line"; done fi } # Prints the movie information out in a human readable format printMovieInfo() { echo echo '+=====================================================+' printKV "Title" "$title" printKV "Year" "$year" printKV "Runtime" "$runtime" if [[ $imdbScore != "" ]]; then printKV "IMDB" "$imdbScore"; fi if [[ $tomatoScore != "" ]]; then printKV "Tomato" "$tomatoScore"; fi if $detail; then if [[ $metacriticScore != "" ]]; then printKV "Metascore" "$metacriticScore"; fi fi if [[ $rated != "N/A" && $rated != "" ]]; then printKV "Rated" "$rated"; fi printKV "Genre" "$genre" printKV "Director" "$director" printKV "Actors" "$actors" if [[ $plot != "N/A" && $plot != "" ]]; then printKV "Plot" "$plot"; fi if $detail; then if [[ $boxOffice != "" ]]; then printKV "BoxOffice" "$boxOffice"; fi if [[ $production != "" ]]; then printKV "Production" "$production"; fi if [[ $awards != "" ]]; then printKV "Awards" "$awards"; fi fi echo '+=====================================================+' echo } update() { # Author: Alexander Epstein https://github.com/alexanderepstein # Update utility version 2.2.0 # To test the tool enter in the defualt values that are in the examples for each variable repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then echo "Error: update utility has not been configured correctly." >&2 exit 1 elif [[ $latestVersion == "" ]]; then echo "Error: no active internet connection" >&2 exit 1 else if [[ "$latestVersion" != "$currentVersion" ]]; then echo "Version $latestVersion available" echo -n "Do you wish to update $repositoryName [Y/n]: " read -r answer if [[ "$answer" == [Yy] ]]; then cd ~ || { echo 'Update Failed'; exit 1; } if [[ -d ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi echo -n "Downloading latest version of: $repositoryName." git clone -q "https://github.com/$githubUserName/$repositoryName" && touch .BSnippetsHiddenFile || { echo "Failure!"; exit 1; } & while [ ! -f .BSnippetsHiddenFile ]; do { echo -n "."; sleep 2; };done rm -f .BSnippetsHiddenFile echo "Success!" cd $repositoryName || { echo 'Update Failed'; exit 1; } git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit." chmod a+x install.sh #this might be necessary in your case but wasnt in mine. ./$nameOfInstallFile "update" || exit 1 cd .. rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; } else exit 1 fi else echo "$repositoryName is already the latest version" fi fi } usage() { cat <&2 exit 1 ;; *) exit 1 ;; esac done if [[ $# == 0 ]]; then usage elif [[ $1 == "update" ]]; then checkInternet || exit 1 # check if we have a valid internet connection if this isnt true the rest of the script will not work so stop here update elif [[ $1 == "help" ]]; then usage else checkInternet || exit 1 # check if we have a valid internet connection if this isnt true the rest of the script will not work so stop here getMovieInfo "$@" || exit 1 ## exit if we return 1 (chances are movie was not found) printMovieInfo ## print out the data fi ================================================ FILE: movies/tmdb ================================================ #!/usr/bin/env bash # Author: Alexander Epstein https://github.com/alexanderepstein # Author: Navan Chauhan https://github.com/navanchauhan currentVersion="1.23.0" configuredClient="" configuredPython="" APIKEY="b2f8880475c888056b6207067fbaa197" ## This function determines which http get tool the system has installed and returns an error if there isnt one getConfiguredClient() { if command -v curl &>/dev/null; then configuredClient="curl" elif command -v wget &>/dev/null; then configuredClient="wget" elif command -v http &>/dev/null; then configuredClient="httpie" elif command -v fetch &>/dev/null; then configuredClient="fetch" else echo "Error: This tool requires either curl, wget, httpie or fetch to be installed." >&2 return 1 fi } ## Allows to call the users configured client without if statements everywhere httpGet() { case "$configuredClient" in curl) curl -A curl -s "$@" ;; wget) wget -qO- "$@" ;; httpie) http -b GET "$@" ;; fetch) fetch -q "$@" ;; esac } getConfiguredPython() { if command -v python2 &>/dev/null ; then configuredPython="python2" elif command -v python &>/dev/null ; then configuredPython="python" else echo "Error: This tool requires python 2 to be installed." return 1 fi } if [[ $(uname) != "Darwin" ]]; then python() { case "$configuredPython" in python2) python2 "$@";; python) python "$@";; esac } fi checkInternet() { httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request } update() { # Author: Alexander Epstein https://github.com/alexanderepstein # Update utility version 1.2.0 # To test the tool enter in the defualt values that are in the examples for each variable repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then echo "Error: update utility has not been configured correctly." >&2 exit 1 elif [[ $latestVersion == "" ]];then echo "Error: no active internet connection" >&2 exit 1 else if [[ "$latestVersion" != "$currentVersion" ]]; then echo "Version $latestVersion available" echo -n "Do you wish to update $repositoryName [Y/n]: " read -r answer if [[ "$answer" == [Yy] ]]; then cd ~ || { echo 'Update Failed' ; exit 1; } if [[ -d ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi git clone "https://github.com/$githubUserName/$repositoryName" || { echo "Couldn't download latest version" ; exit 1; } cd $repositoryName || { echo 'Update Failed' ; exit 1; } git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit." chmod a+x install.sh #this might be necessary in your case but wasnt in mine. ./$nameOfInstallFile "update" || exit 1 cd .. rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; } else exit 1 fi else echo "$repositoryName is already the latest version" fi fi } printMovieInfo() { echo echo "==========================================" echo "| Title: $name" echo "| Language: $language" echo "| Genre: $genres" echo "| Runtime: $runtime mins" echo "| User Rating: $voteAverage/10.0 with $voteCount votes" echo "| Plot: $plot" echo "==========================================" echo } usage() { cat < /dev/null) if [[ $movieID == "" ]];then { echo "Error: could not find a movie matching the title $title"; return 1; }; fi movieInfo=$(httpGet "https://api.themoviedb.org/3/movie/$movieID?api_key=$APIKEY") name=$(echo "$movieInfo" | python -c "import sys, json; print json.load(sys.stdin)['original_title']" 2> /dev/null ) plot=$(echo "$movieInfo" | python -c "import sys, json; print json.load(sys.stdin)['overview']" 2> /dev/null ) language=$(echo "$movieInfo" | python -c "import sys, json; print json.load(sys.stdin)['original_language']" 2> /dev/null ) runtime=$(echo "$movieInfo" | python -c "import sys, json; print json.load(sys.stdin)['runtime']" 2> /dev/null ) voteCount=$(echo "$movieInfo" | python -c "import sys, json; print json.load(sys.stdin)['vote_count']" 2> /dev/null ) genreOne=$(echo "$movieInfo" | python -c "import sys, json; print json.load(sys.stdin)['genres'][0]['name']" 2> /dev/null ) genreTwo=$(echo "$movieInfo" | python -c "import sys, json; print json.load(sys.stdin)['genres'][1]['name']" 2> /dev/null ) genreThree=$(echo "$movieInfo" | python -c "import sys, json; print json.load(sys.stdin)['genres'][2]['name']" 2> /dev/null ) genres=$(echo "$genreOne $genreTwo $genreThree" | tr " " ",") voteAverage=$(echo "$movieInfo" | python -c "import sys, json; print json.load(sys.stdin)['vote_average']" 2> /dev/null ) } getConfiguredClient || exit 1 if [[ "$(uname)" == "Linux" ]];then getConfiguredPython || exit 1; fi checkInternet || exit 1 while getopts 'uhv' flag; do case "${flag}" in u) update exit 0 ;; h) usage exit 0 ;; v) echo "Version $currentVersion" exit 0 ;; :) echo "Option -$OPTARG requires an argument." >&2 exit 1 ;; *) exit 1 ;; esac done if [[ $# == 0 ]]; then usage elif [[ $1 == "update" ]]; then update elif [[ $1 == "help" ]]; then usage else getMovieInfo "$@" || exit 1 ## exit if we return 1 (chances are movie was not found) printMovieInfo ## print out the data fi ================================================ FILE: newton/newton ================================================ #!/usr/bin/env bash # Author: Alexander Epstein https://github.com/alexanderepstein currentVersion="1.23.0" configuredClient="" flagCount="0" declare -a simpleOperations=(simplify factor derive integrate zeroes roots tangent area cos sin tan arccos arcsin arctan abs log) ## This function determines which http get tool the system has installed and returns an error if there isnt one getConfiguredClient() { if command -v curl &>/dev/null; then configuredClient="curl" elif command -v wget &>/dev/null; then configuredClient="wget" elif command -v http &>/dev/null; then configuredClient="httpie" elif command -v fetch &>/dev/null; then configuredClient="fetch" else echo "Error: This tool requires either curl, wget, httpie or fetch to be installed." >&2 return 1 fi } ## Allows to call the users configured client without if statements everywhere httpGet() { case "$configuredClient" in curl) curl -A curl -s "$@" ;; wget) wget -qO- "$@" ;; httpie) http -b GET "$@" ;; fetch) fetch -q "$@" ;; esac } checkInternet() { httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request } update() { # Author: Alexander Epstein https://github.com/alexanderepstein # Update utility version 2.2.0 # To test the tool enter in the defualt values that are in the examples for each variable repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then echo "Error: update utility has not been configured correctly." >&2 exit 1 elif [[ $latestVersion == "" ]]; then echo "Error: no active internet connection" >&2 exit 1 else if [[ "$latestVersion" != "$currentVersion" ]]; then echo "Version $latestVersion available" echo -n "Do you wish to update $repositoryName [Y/n]: " read -r answer if [[ "$answer" == [Yy] ]]; then cd ~ || { echo 'Update Failed'; exit 1; } if [[ -d ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi echo -n "Downloading latest version of: $repositoryName." git clone -q "https://github.com/$githubUserName/$repositoryName" && touch .BSnippetsHiddenFile || { echo "Failure!"; exit 1; } & while [ ! -f .BSnippetsHiddenFile ]; do { echo -n "."; sleep 2; };done rm -f .BSnippetsHiddenFile echo "Success!" cd $repositoryName || { echo 'Update Failed'; exit 1; } git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit." chmod a+x install.sh #this might be necessary in your case but wasnt in mine. ./$nameOfInstallFile "update" || exit 1 cd .. rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; } else exit 1 fi else echo "$repositoryName is already the latest version" fi fi } validateExpression() { local parsedExpression # only used here originalEquation=$(echo "$1" | sed "s/\[/\(/g" | sed "s/\]/\)/g") # accont for the fact that we have to use brackets and not parenthesis parsedExpression=$(echo "$1" | sed "s/\[/\(/g" | sed "s/\]/\)/g" | grep -Eo "[0-9 + -- / * ^ . a-z A-Z ~ : ( ) ]*") # only grepping valid characters if [ "$parsedExpression" != "$originalEquation" ];then { echo "Error: Expression contains invalid characters"; return 1; }; fi # compare result to original return 0 } encodeEquation() { equation=$(echo "$originalEquation" | sed "s:/:(over):g" | sed "s/~/|/g" | sed "s/-/%2D/g") # encode all the special characters } validateOperation() { operation=$(echo "$1" | tr "[[:upper:]]" "[[:lower:]]") # get rid of case being an issue validOp="false" # lets us know if oeration is valid for op in "${simpleOperations[@]}"; do # go through all valid simple operations if [[ "$op" == "$operation" ]]; then { opType="simple"; validOp="true"; break; }; fi # if the operation matches leave the loop done if ! $validOp; then { echo "Error: invalid operation, run newton -h to get a list of valid operations"; return 1; }; fi # if not a valid operation error out if [[ $operation == "roots" ]]; then operation=zeroes;fi # I gave the ability to use root or zeores but real op is zeroes } getSimpleResponse() { result=$(httpGet https://newton.now.sh/api/v2/$operation/"$equation" | grep -Eo '"result":"[a-z A-Z 0-9 ( ) \^ / -- + , ]*' | sed s/'"result":"'//g | tr '"' " ") # get reponse, grab result if [[ $result == "" ]];then { echo "Error: no result was returned, did you use valid characters?"; return 1; }; fi # if result is empty sometthing went wrong... } printAnswer() { cat <&2 exit 1 ;; h) usage exit 0 ;; v) echo "Version $currentVersion" exit 0 ;; u) update exit 0 ;; r) resultOnly="true" && flagCount=$((flagCount + 1 ));; :) echo "Option -$OPTARG requires an argument." >&2 exit 1 ;; esac done if [[ $# == "0" ]]; then usage && exit 0 elif [[ $# == "1" ]]; then if [[ $1 == "update" ]]; then checkInternet && update && exit 0 || exit 1 elif [[ $1 == "help" ]]; then usage && exit 0 || exit 1 else echo "Error: newton needs two arguments, operation and expression" && exit 1;fi elif [ $# -gt 3 ];then echo "Error: newton only accepts two arguments, operation and expression" && exit 1;fi # flagCount helps us determine what argument to pass to the functions # flow: validateOperation, validateExpression, encodeEquation, getResponse, print Answer/Result checkInternet || exit 1 if [[ $flagCount == "0" ]];then validateOperation "$1" || exit 1 elif [[ $flagCount == "1" ]];then validateOperation "$2" || exit 1; fi if [[ $flagCount == "0" ]];then validateExpression "$2" || exit 1 elif [[ $flagCount == "1" ]];then validateExpression "$3" || exit 1; fi encodeEquation || exit 1 if [[ $opType == "simple" ]];then getSimpleResponse || exit 1;fi if [ -z $resultOnly ];then printAnswer else echo "$result"; fi ================================================ FILE: pwned/pwned ================================================ #!/usr/bin/env bash # Author: Navan Chauhan https://github.com/navanchauhan currentVersion="1.23.0" configuredClient="" configuredPython="" ## This function determines which http get tool the system has installed and returns an error if there isnt one getConfiguredClient() { if command -v curl &>/dev/null; then configuredClient="curl" elif command -v wget &>/dev/null; then configuredClient="wget" elif command -v http &>/dev/null; then configuredClient="httpie" elif command -v fetch &>/dev/null; then configuredClient="fetch" else echo "Error: This tool requires either curl, wget, httpie or fetch to be installed." >&2 return 1 fi } ## Allows to call the users configured client without if statements everywhere httpGet() { case "$configuredClient" in curl) curl -A curl -s "$@" ;; wget) wget -qO- "$@" ;; httpie) http -b GET "$@" ;; fetch) fetch -q "$@" ;; esac } getConfiguredPython() { if command -v python3 &>/dev/null; then configuredPython="python3" elif command -v python2 &>/dev/null; then configuredPython="python2" elif command -v python &>/dev/null; then configuredPython="python" else echo "Error: This tool requires python to be installed." return 1 fi } if [[ $(uname) != "Darwin" ]]; then python() { case "$configuredPython" in python2) python2 "$@" ;; python) python "$@" ;; esac } fi checkInternet() { httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request } ## This function grabs data from Have I been Pwned ? and using python parses it ## JSON response to extrapolate the information for storage getPwned() { info=$(httpGet "https://haveibeenpwned.com/api/v2/breachedaccount/$1") > /dev/null #grab the JSON response export PYTHONIOENCODING=utf8 #necessary for python in some cases echo "$info" | python -c "from __future__ import print_function; import sys, json; print(sys.stdin)[0]['Title'])" > /dev/null 2>&1 || { echo "Looks like you have not been breached"; exit 1; } # # The rest of the code is just extrapolating the data with python from the JSON response echo "$info" > .pwned.json title=$(python -c "from __future__ import print_function; import sys, json; print('\n'.join([u['Title']for u in json.load(open(sys.argv[1]))]))" ".pwned.json") rm -f .pwned.json unset info # done with the JSON response not needed anymore } printPwned() { echo echo "=============================================" echo "$1 has beeen breached at:" echo "$title" echo "=============================================" echo } update() { # Author: Alexander Epstein https://github.com/alexanderepstein # Update utility version 2.2.0 # To test the tool enter in the defualt values that are in the examples for each variable repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then echo "Error: update utility has not been configured correctly." >&2 exit 1 elif [[ $latestVersion == "" ]]; then echo "Error: no active internet connection" >&2 exit 1 else if [[ "$latestVersion" != "$currentVersion" ]]; then echo "Version $latestVersion available" echo -n "Do you wish to update $repositoryName [Y/n]: " read -r answer if [[ "$answer" == [Yy] ]]; then cd ~ || { echo 'Update Failed'; exit 1; } if [[ -d ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi echo -n "Downloading latest version of: $repositoryName." git clone -q "https://github.com/$githubUserName/$repositoryName" && touch .BSnippetsHiddenFile || { echo "Failure!"; exit 1; } & while [ ! -f .BSnippetsHiddenFile ]; do { echo -n "."; sleep 2; };done rm -f .BSnippetsHiddenFile echo "Success!" cd $repositoryName || { echo 'Update Failed'; exit 1; } git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit." chmod a+x install.sh #this might be necessary in your case but wasnt in mine. ./$nameOfInstallFile "update" || exit 1 cd .. rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; } else exit 1 fi else echo "$repositoryName is already the latest version" fi fi } usage() { cat <&2 exit 1 ;; h) usage exit 0 ;; v) echo "Version $currentVersion" exit 0 ;; u) checkInternet || exit 1 update exit 0 ;; :) echo "Option -$OPTARG requires an argument." >&2 exit 1 ;; esac done if [[ $1 == "update" ]]; then checkInternet || exit 1 update exit 0 elif [[ $1 == "help" ]]; then usage exit 0 elif [[ $# == "0" ]]; then usage exit 0 else checkInternet || exit 1 getPwned "$1" # based on the stock symbol exrapolated by the getTicker function get information on the stock printPwned "$1" # print this information out to the user in a human readable format exit 0 fi ================================================ FILE: qrify/qrify ================================================ #!/usr/bin/env bash # Author: Linyos Torovoltos github.com/linyostorovovoltos currentVersion="1.23.0" multiline="0" # flag that indicates multiline option fileoutput="0" # flag indicating the -f option ## This function determines which http get tool the system has installed and returns an error if there isnt one getConfiguredClient() { if command -v curl &>/dev/null; then configuredClient="curl" elif command -v wget &>/dev/null; then configuredClient="wget" elif command -v http &>/dev/null; then configuredClient="httpie" elif command -v fetch &>/dev/null; then configuredClient="fetch" else echo "Error: This tool requires either curl, wget, httpie or fetch to be installed." >&2 return 1 fi } ## Allows to call the users configured client without if statements everywhere httpGet() { case "$configuredClient" in curl) curl -A curl -s "$@" ;; wget) wget -qO- "$@" ;; httpie) http -b GET "$@" ;; fetch) fetch -q "$@" ;; esac } getConfiguredPython() { if command -v python3 &>/dev/null; then configuredPython="python3" elif command -v python2 &>/dev/null; then configuredPython="python2" elif command -v python &>/dev/null; then configuredPython="python" else echo "Error: This tool requires python to be installed." return 1 fi } if [[ $(uname) != "Darwin" ]]; then python() { case "$configuredPython" in python3) python3 "$@" ;; python2) python2 "$@" ;; python) python "$@" ;; esac } fi update() { # Author: Alexander Epstein https://github.com/alexanderepstein # Update utility version 2.2.0 # To test the tool enter in the defualt values that are in the examples for each variable repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then echo "Error: update utility has not been configured correctly." >&2 exit 1 elif [[ $latestVersion == "" ]]; then echo "Error: no active internet connection" >&2 exit 1 else if [[ "$latestVersion" != "$currentVersion" ]]; then echo "Version $latestVersion available" echo -n "Do you wish to update $repositoryName [Y/n]: " read -r answer if [[ "$answer" == [Yy] ]]; then cd ~ || { echo 'Update Failed'; exit 1; } if [[ -d ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi echo -n "Downloading latest version of: $repositoryName." git clone -q "https://github.com/$githubUserName/$repositoryName" && touch .BSnippetsHiddenFile || { echo "Failure!"; exit 1; } & while [ ! -f .BSnippetsHiddenFile ]; do { echo -n "."; sleep 2; };done rm -f .BSnippetsHiddenFile echo "Success!" cd $repositoryName || { echo 'Update Failed'; exit 1; } git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit." chmod a+x install.sh #this might be necessary in your case but wasnt in mine. ./$nameOfInstallFile "update" || exit 1 cd .. rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; } else exit 1 fi else echo "$repositoryName is already the latest version" fi fi } makeqr() { input=$(echo "$input" | sed s/" "/%20/g ) ## replace all spaces in the sentence with HTML-encoded space %20 httpGet qrenco.de/"$input" ## get a response for the qrcode } # redirects the image obtained from the goqr api into a png file makeQRFile() { input=$(echo "$input" | sed -e s/" "/%20/g -e s/'\\n'/%0A/g ) ##same as in the makeqr function addFileExt httpGet "api.qrserver.com/v1/create-qr-code/?size=150x150&data=$input" > "$fileName" } addFileExt() { if ! echo "$fileName" | grep -E -q ".*\.png$|.*\.PNG$" then fileName="$fileName.png" fi } makeMultiLineQr() { if [[ ${configuredClient} != "curl" ]]; then ## prevent usage without curl it is unreliable echo "Multiline currently only supports curl!" return 1 else input=$(echo "$input" | sed -e s/" "/%20/g -e s/'\\n'/%0A/g ) ##same as in the makeqr function printf "%s" "$input" | curl -F-=\<- qrenco.de fi } # Function to get the json response from POST request decodeQR() { local qrFile="$1" if ! echo "$fileName" | grep -E -q ".*\.png$|.*\.PNG$|.*\.gif$|.*\.jpg$|.*\.jpeg$|.*\.GIF$|.*\.JPG$|.*\.JPEG$" then exit 1 fi # only uses curl # Cannot use wget because it does not support multipart/form-data (as per the man page)] case "$configuredClient" in curl) JSONresponse=$(curl -s -F "file=@$qrFile" http://api.qrserver.com/v1/read-qr-code/) || exit 1;; wget) echo "Error:-Not supported with wget" >&2 && exit 1;; httpie) JSONresponse=$(http -b --form POST http://api.qrserver.com/v1/read-qr-code/ file@"$qrFile") || exit 1;; fetch) echo "Error:-Not supported with wget" >&2 && exit 1;; esac error="$(echo "$JSONresponse" | python -c "from __future__ import print_function; import sys, json; print(json.load(sys.stdin)[0]['symbol'][0]['error'])")" if [[ "$error" == "None" ]] then data="$(echo "$JSONresponse" | python -c "from __future__ import print_function; import sys, json; print(json.load(sys.stdin)[0]['symbol'][0]['data'])")" else echo "Error:-$error" >&2 && exit 1 fi } checkInternet() { httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request } usage() { cat </dev/null; then configuredClient="curl" elif command -v wget &>/dev/null; then configuredClient="wget" elif command -v http &>/dev/null; then configuredClient="httpie" elif command -v fetch &>/dev/null; then configuredClient="fetch" else echo "Error: This tool requires either curl, wget, httpie or fetch to be installed." >&2 return 1 fi } ## Allows to call the users configured client without if statements everywhere httpGet() { case "$configuredClient" in curl) curl -A curl -s "$@" ;; wget) wget -qO- "$@" ;; httpie) http -b GET "$@" ;; fetch) fetch -q "$@" ;; esac } checkInternet() { httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request } update() { # Author: Alexander Epstein https://github.com/alexanderepstein # Update utility version 2.2.0 # To test the tool enter in the defualt values that are in the examples for each variable repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then echo "Error: update utility has not been configured correctly." >&2 exit 1 elif [[ $latestVersion == "" ]]; then echo "Error: no active internet connection" >&2 exit 1 else if [[ "$latestVersion" != "$currentVersion" ]]; then echo "Version $latestVersion available" echo -n "Do you wish to update $repositoryName [Y/n]: " read -r answer if [[ "$answer" == [Yy] ]]; then cd ~ || { echo 'Update Failed'; exit 1; } if [[ -d ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi echo -n "Downloading latest version of: $repositoryName." git clone -q "https://github.com/$githubUserName/$repositoryName" && touch .BSnippetsHiddenFile || { echo "Failure!"; exit 1; } & while [ ! -f .BSnippetsHiddenFile ]; do { echo -n "."; sleep 2; };done rm -f .BSnippetsHiddenFile echo "Success!" cd $repositoryName || { echo 'Update Failed'; exit 1; } git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit." chmod a+x install.sh #this might be necessary in your case but wasnt in mine. ./$nameOfInstallFile "update" || exit 1 cd .. rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; } else exit 1 fi else echo "$repositoryName is already the latest version" fi fi } usage() { cat <&2 exit 1 ;; e) expand="true" inputURL=$OPTARG ;; s) shorten="true" inputURL=$OPTARG ;; h) usage exit 0 ;; v) echo "Version $currentVersion" exit 0 ;; u) checkInternet || exit 1 update exit 0 ;; :) echo "Option -$OPTARG requires an argument." >&2 exit 1 ;; esac done if [[ $expand == "true" && $shorten == "true" ]];then echo "Error: the -e and the -s options are mutually exclusive" >&2 exit 1 fi if [[ $# == 0 ]]; then usage exit 0 elif [[ $# == "1" ]]; then if [[ $1 == "update" ]]; then checkInternet || exit 1 update elif [[ $1 == "help" ]]; then usage else usage exit 1 fi elif [[ $expand == "true" ]];then checkInternet || exit 1 expandURL "$inputURL" || exit 1 printResults elif [[ $shorten == "true" ]];then if [[ $configuredClient != "curl" ]];then echo "Error: to shorten URLS you must have curl installed" fi checkInternet || exit 1 shortenURL "$inputURL" printShortenedResults else echo "Error: short only accepts one argument" exit 1 fi ================================================ FILE: siteciphers/siteciphers ================================================ #!/usr/bin/env bash DELAY=1 configuredClient="" currentVersion="1.23.0" checkOpenSSL() { if ! command -v openssl &>/dev/null; then echo "Error: to use this tool openssl must be installed" >&2 return 1 else return 0 fi } ## This function determines which http get tool the system has installed and returns an error if there isnt one getConfiguredClient() { if command -v curl &>/dev/null; then configuredClient="curl" elif command -v wget &>/dev/null; then configuredClient="wget" elif command -v http &>/dev/null; then configuredClient="httpie" elif command -v fetch &>/dev/null; then configuredClient="fetch" else echo "Error: This tool requires either curl, wget, httpie or fetch to be installed." >&2 return 1 fi } ## Allows to call the users configured client without if statements everywhere httpGet() { case "$configuredClient" in curl) curl -A curl -s "$@" ;; wget) wget -qO- "$@" ;; httpie) http -b GET "$@" ;; fetch) fetch -q "$@" ;; esac } update() { # Author: Alexander Epstein https://github.com/alexanderepstein # Update utility version 2.2.0 # To test the tool enter in the defualt values that are in the examples for each variable repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then echo "Error: update utility has not been configured correctly." >&2 exit 1 elif [[ $latestVersion == "" ]]; then echo "Error: no active internet connection" >&2 exit 1 else if [[ "$latestVersion" != "$currentVersion" ]]; then echo "Version $latestVersion available" echo -n "Do you wish to update $repositoryName [Y/n]: " read -r answer if [[ "$answer" == [Yy] ]]; then cd ~ || { echo 'Update Failed'; exit 1; } if [[ -d ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi echo -n "Downloading latest version of: $repositoryName." git clone -q "https://github.com/$githubUserName/$repositoryName" && touch .BSnippetsHiddenFile || { echo "Failure!"; exit 1; } & while [ ! -f .BSnippetsHiddenFile ]; do { echo -n "."; sleep 2; };done rm -f .BSnippetsHiddenFile echo "Success!" cd $repositoryName || { echo 'Update Failed'; exit 1; } git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit." chmod a+x install.sh #this might be necessary in your case but wasnt in mine. ./$nameOfInstallFile "update" || exit 1 cd .. rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; } else exit 1 fi else echo "$repositoryName is already the latest version" fi fi } usage() { cat < /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request } checkCiphers() { ciphers=$(openssl ciphers 'ALL:eNULL' | sed -e 's/:/ /g') # grab all ciphers SERVER=$1:443 # setup the connection server for cipher in ${ciphers[*]}; do # for all possible ciphers result=$(echo | openssl s_client -cipher "$cipher" -connect "$SERVER" 2>&1) if [[ "$result" =~ ":error:" ]]; then if [[ -z $2 ]]; then error=$(echo -n "$result" | cut -d':' -f6) echo "$cipher - NO ($error)" fi else if [[ "$result" =~ "Cipher is $cipher" || "$result" =~ "Cipher :" ]]; then echo "$cipher - YES" else if [[ -z $2 ]]; then echo "$cipher - UNKNOWN RESPONSE - $result" fi fi fi sleep $DELAY # sleep as to not overload the requests to the server done } checkOpenSSL || exit 1 getConfiguredClient || exit 1 if [[ $# == "0" ]]; then usage exit 1 elif [[ $1 == "update" ]]; then checkInternet || exit 1 update exit 0 elif [[ $1 == "help" ]]; then usage exit 0 fi while getopts "huvd:" opt; do ## alows for using options in bash case "$opt" in \?) echo "Invalid option: -$OPTARG" >&2 exit 1 ;; d) #set the delay with the -d option DELAY=$OPTARG dFlag="1" ;; u) checkInternet || exit 1 update exit 0 ;; h) usage exit 0 ;; v) echo "Version $currentVersion" exit 0 ;; :) ## will run when no arguments are provided to to d options echo "Option -$OPTARG requires an argument." >&2 exit 1 ;; esac done checkInternet || exit 1 if [[ $dFlag == "1" ]]; then checkCiphers "$3" || exit 1 # if dflag is present input will look like siteciphers -d 0.5 github.com making the website the third arg else checkCiphers "$1" || exit 1 fi ================================================ FILE: skeleton ================================================ #!/usr/bin/env bash # Author: Alexander Epstein https://github.com/alexanderepstein currentVersion="1.23.0" configuredClient="" ## This function determines which http get tool the system has installed and returns an error if there isnt one getConfiguredClient() { if command -v curl &>/dev/null; then configuredClient="curl" elif command -v wget &>/dev/null; then configuredClient="wget" elif command -v http &>/dev/null; then configuredClient="httpie" elif command -v fetch &>/dev/null; then configuredClient="fetch" else echo "Error: This tool requires either curl, wget, httpie or fetch to be installed." >&2 return 1 fi } # The python and JSON functions can be deleted if the script does not need them ## This function determines which version of python is installed on the machine getConfiguredPython() { if command -v python3 &>/dev/null; then configuredPython="python3" elif command -v python2 &>/dev/null; then configuredPython="python2" elif command -v python &>/dev/null; then configuredPython="python" else echo "Error: This tool requires python to be installed." return 1 fi } ## Don't alter the python call if it's coming from a Mac if [[ $(uname) != "Darwin" ]]; then python() { case "$configuredPython" in python3) python3 "$@" ;; python2) python2 "$@" ;; python) python "$@" ;; esac } fi ## Grabs an element from a a json string and then echoes it to stdout ## $1 = the JSON string ## $n+1 = the elements to be indexed AccessJsonElement() { json="$1" shift accessor="" for element in "$@"; do accessor="${accessor}['$element']" done echo "$json" | python -c "from __future__ import print_function; import sys, json; print(json.load(sys.stdin)${accessor})" return "$?" } ## Allows to call the users configured client without if statements everywhere httpGet() { case "$configuredClient" in curl) curl -A curl -s "$@" ;; wget) wget -qO- "$@" ;; httpie) http -b GET "$@" ;; fetch) fetch -q "$@" ;; esac } update() { # Author: Alexander Epstein https://github.com/alexanderepstein # Update utility version 1.2.0 # To test the tool enter in the default values that are in the examples for each variable repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then echo "Error: update utility has not been configured correctly." >&2 exit 1 elif [[ $latestVersion == "" ]]; then echo "Error: no active internet connection" >&2 exit 1 else if [[ "$latestVersion" != "$currentVersion" ]]; then echo "Version $latestVersion available" echo -n "Do you wish to update $repositoryName [Y/n]: " read -r answer if [[ "$answer" == [Yy] ]]; then cd ~ || { echo 'Update Failed'; exit 1; } if [[ -d ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi git clone "https://github.com/$githubUserName/$repositoryName" || { echo "Couldn't download latest version"; exit 1; } cd $repositoryName || { echo 'Update Failed'; exit 1; } git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit." chmod a+x install.sh #this might be necessary in your case but wasnt in mine. ./$nameOfInstallFile "update" || exit 1 cd .. rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; } else exit 1 fi else echo "$repositoryName is already the latest version" fi fi } checkInternet() { httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request } usage() { cat <&2 exit 1 ;; h) usage exit 0 ;; v) echo "Version $currentVersion" exit 0 ;; u) getConfiguredClient || exit 1 checkInternet || exit 1 update exit 0 ;; :) echo "Option -$OPTARG requires an argument." >&2 exit 1 ;; esac done # special set of first arguments that have a specific behavior across tools if [[ $# == "0" ]]; then usage ## if calling the tool with no flags and args chances are you want to return usage exit 0 elif [[ $# == "1" ]]; then if [[ $1 == "update" ]]; then getConfiguredClient || exit 1 checkInternet || exit 1 update || exit 1 exit 0 elif [[ $1 == "help" ]]; then usage exit 0 fi fi ## The rest of the conditions and code would go here ## Make sure to use checkInternet at least once before any time httpGet will be called. ## Make sure to call getConfiguredClient at least once before ever calling checkInternet. ## Make sure to call getConfiguredPython at least once before trying to pipeout to python directly or using AccessJsonElement ================================================ FILE: skeleton.bats ================================================ #!/usr/bin/env bats export TOOL_NAME='skeleton' setup() { # $REPO_DIR/tests/skeleton.bats REPO_DIR="$( cd "$( dirname "${BATS_TEST_DIRNAME}")" >/dev/null 2>&1 && pwd)" TOOL_DIR="$( cd "${REPO_DIR}/${TOOL_NAME}" >/dev/null 2>&1 && pwd)" } @test "Testing ${TOOL_NAME} tool" { echo "${TOOL_NAME}" } @test "Confirm the \$REPO_DIR variable is evaluated" { cd "${REPO_DIR}" && pwd [[ "$status" -eq 0 ]] } @test "Change into the tool directory for ${TOOL_NAME}" { cd "${TOOL_DIR}" && pwd [[ "$status" -eq 0 ]] } @test "Check for latest version of bash-snippets on update" { if [[ "$(uname)" == "Linux" ]]; then run "${TOOL_DIR}/${TOOL_NAME}" update [[ "$status" -eq 0 ]] [ "$output" == "Bash-Snippets is already the latest version" ] fi } @test "The -h option should print usage" { run "${TOOL_DIR}/${TOOL_NAME}" -h [[ "$status" -eq 0 ]] # if bash is less than 7 yrs old if ((${BASH_VERSINFO[0]} >= 4)); then [[ "${lines[0]}" = "${TOOL_NAME^}" ]] else # or im probably a stoneage mac [[ "$(echo "${output}" | grep -i "${TOOL_NAME}")" ]] fi } @test "No arguments prints usage instructions" { run "${TOOL_DIR}/${TOOL_NAME}" [[ "$status" -eq 0 ]] # if bash is less than 7 yrs old if ((${BASH_VERSINFO[0]} >= 4)); then [[ "${lines[0]}" = "${TOOL_NAME^}" ]] else # or im probably a stoneage mac [[ "$(echo "${output}" | grep -i "${TOOL_NAME}")" ]] fi } @test "Get the tools version with -v" { run "${TOOL_DIR}/${TOOL_NAME}" -v [[ "$status" -eq 0 ]] expected='Version' [[ "${output}" =~ "${expected}" ]] } # Tool specific tests @test "Do that cool thing" { run "${TOOL_DIR}/${TOOL_NAME}" cool [[ "$status" -eq 0 ]] expected='This is awesome' [[ "${output}" =~ "${expected}" ]] } @test "Testing coolness factor" { run "${TOOL_DIR}/${TOOL_NAME}" cool --even-cooler [[ "$status" -eq 0 ]] expected='subzero' [[ "printf '%s\n' ${lines[1]}" =~ "${expected}" ]] } ================================================ FILE: stocks/stocks ================================================ #!/usr/bin/env bash # Author: Alexander Epstein https://github.com/alexanderepstein # Author: Navan Chauhan https://github.com/navanchauhan # Author: Tyler Stubenvoll https://github.com/tjstub currentVersion="1.23.0" configuredClient="" configuredPython="" ## This function determines which http get tool the system has installed and returns an error if there isnt one getConfiguredClient() { if command -v curl &>/dev/null; then configuredClient="curl" elif command -v wget &>/dev/null; then configuredClient="wget" elif command -v http &>/dev/null; then configuredClient="httpie" elif command -v fetch &>/dev/null; then configuredClient="fetch" else echo "Error: This tool requires either curl, wget, httpie or fetch to be installed." >&2 return 1 fi } ## Allows to call the users configured client without if statements everywhere httpGet() { case "$configuredClient" in curl) curl -A curl -s "$@" ;; wget) wget -qO- "$@" ;; httpie) http -b GET "$@" ;; fetch) fetch -q "$@" ;; esac } getConfiguredPython() { if command -v python3 &>/dev/null; then configuredPython="python3" elif command -v python2 &>/dev/null; then configuredPython="python2" elif command -v python &>/dev/null; then configuredPython="python" else echo "Error: This tool requires python to be installed." return 1 fi } if [[ $(uname) != "Darwin" ]]; then python() { case "$configuredPython" in python3) python3 "$@" ;; python2) python2 "$@" ;; python) python "$@" ;; esac } fi checkInternet() { httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request } ## Grabs an element from a a json string and then echoes it to stdout ## $1 = the JSON string ## $n+1 = the elements to be indexed AccessJsonElement() { json="$1" shift accessor="" for element in "$@"; do accessor="${accessor}['$element']" done echo "$json" | python -c "from __future__ import print_function; import sys, json; print(json.load(sys.stdin)${accessor})" return "$?" } ## This function grabs information about a stock and prints it for consumption printStockInformation() { # this data is updated hourly. stockProfile="$(httpGet "https://financialmodelingprep.com/api/v3/company/profile/${1}")" > /dev/null # this is realtime data. stockPrice="$(httpGet "https://financialmodelingprep.com/api/v3/stock/real-time-price/${1}")" > /dev/null # necessary for python in some cases export PYTHONIOENCODING=utf8 # checking if we get any information back from the server if not # chances are it isnt a valid stock symbol AccessJsonElement "$stockProfile" "profile" "companyName" > /dev/null 2>&1 \ || { echo "$1: Not a valid stock symbol"; exit 1; } # The rest of the code is just extrapolating the data with python # from the JSON response name="$(AccessJsonElement "$stockProfile" "profile" "companyName")" exchangeName="$(AccessJsonElement "$stockProfile" "profile" "exchange")" latestPrice="$(AccessJsonElement "$stockPrice" "price")" range="$(AccessJsonElement "$stockProfile" "profile" "range")" priceChange="$(AccessJsonElement "$stockProfile" "profile" "changes")" priceChangePercentage="$(AccessJsonElement "$stockProfile" "profile" "changesPercentage")" volumeAvg="$(AccessJsonElement "$stockProfile" "profile" "volAvg")" cat < /dev/null # using python to extrapolate the stock symbol symbol="$(echo "$response" | python -c "from __future__ import print_function; import sys, json; print(json.load(sys.stdin)['ResultSet']['Result'][0]['symbol'])")" # just unsets the entire response after using it since all I need is the stock ticker unset response } update() { # Author: Alexander Epstein https://github.com/alexanderepstein # Update utility version 2.2.0 # To test the tool enter in the defualt values that are in the examples for each variable repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then echo "Error: update utility has not been configured correctly." >&2 exit 1 elif [[ $latestVersion == "" ]]; then echo "Error: no active internet connection" >&2 exit 1 else if [[ "$latestVersion" != "$currentVersion" ]]; then echo "Version $latestVersion available" echo -n "Do you wish to update $repositoryName [Y/n]: " read -r answer if [[ "$answer" == [Yy] ]]; then cd ~ || { echo 'Update Failed'; exit 1; } if [[ -d ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi echo -n "Downloading latest version of: $repositoryName." git clone -q "https://github.com/$githubUserName/$repositoryName" && touch .BSnippetsHiddenFile || { echo "Failure!"; exit 1; } & while [ ! -f .BSnippetsHiddenFile ]; do { echo -n "."; sleep 2; };done rm -f .BSnippetsHiddenFile echo "Success!" cd $repositoryName || { echo 'Update Failed'; exit 1; } git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit." chmod a+x install.sh #this might be necessary in your case but wasnt in mine. ./$nameOfInstallFile "update" || exit 1 cd .. rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; } else exit 1 fi else echo "$repositoryName is already the latest version" fi fi } usage() { cat <&2 exit 1 ;; h) usage exit 0 ;; v) echo "Version $currentVersion" exit 0 ;; u) checkInternet || exit 1 update exit 0 ;; :) echo "Option -$OPTARG requires an argument." >&2 exit 1 ;; esac done if [[ $1 == "update" ]]; then checkInternet || exit 1 update exit 0 elif [[ $1 == "help" ]]; then usage exit 0 elif [[ $# == "0" ]]; then usage exit 0 else checkInternet || exit 1 # the company name might have spaces so passing in all args allows for this getTicker "$@" # based on the stock symbol exrapolated by the getTicker function get # information on the stock printStockInformation "$symbol" exit 0 fi ================================================ FILE: taste/taste ================================================ #!/usr/bin/env bash # Author: Alexander Epstein https://github.com/alexanderepstein currentVersion="1.23.0" configuredClient="" configuredPython="" source ~/.bash_profile 2> /dev/null ## allows grabbing enviornment variable apiKey=$TASTE_API_KEY info="0" ## indicates if we want extra info search="0" ## indivates that we want results on the item itself ## This function determines which http get tool the system has installed and returns an error if there isnt one getConfiguredClient() { if command -v curl &>/dev/null; then configuredClient="curl" elif command -v wget &>/dev/null; then configuredClient="wget" elif command -v http &>/dev/null; then configuredClient="httpie" elif command -v fetch &>/dev/null; then configuredClient="fetch" else echo "Error: This tool requires either curl, wget, httpie or fetch to be installed." >&2 return 1 fi } ## Allows to call the users configured client without if statements everywhere httpGet() { case "$configuredClient" in curl) curl -A curl -s "$@" ;; wget) wget -qO- "$@" ;; httpie) http -b GET "$@" ;; fetch) fetch -q "$@" ;; esac } getConfiguredPython() { if command -v python3 &>/dev/null; then configuredPython="python3" elif command -v python2 &>/dev/null; then configuredPython="python2" elif command -v python &>/dev/null; then configuredPython="python" else echo "Error: This tool requires python to be installed." return 1 fi } if [[ $(uname) != "Darwin" ]]; then python() { case "$configuredPython" in python3) python3 "$@" ;; python2) python2 "$@" ;; python) python "$@" ;; esac } fi ## Grabs an element from a a json string and then echoes it to stdout ## $1 = the JSON string ## $n+1 = the elements to be indexed AccessJsonElement() { json="$1" shift accessor="" for element in "$@"; do accessor="${accessor}['$element']" done echo "$json" | python -c "from __future__ import print_function; import sys, json; print(json.load(sys.stdin)${accessor})" return "$?" } checkInternet() { httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request } update() { # Author: Alexander Epstein https://github.com/alexanderepstein # Update utility version 2.2.0 # To test the tool enter in the defualt values that are in the examples for each variable repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then echo "Error: update utility has not been configured correctly." >&2 exit 1 elif [[ $latestVersion == "" ]]; then echo "Error: no active internet connection" >&2 exit 1 else if [[ "$latestVersion" != "$currentVersion" ]]; then echo "Version $latestVersion available" echo -n "Do you wish to update $repositoryName [Y/n]: " read -r answer if [[ "$answer" == [Yy] ]]; then cd ~ || { echo 'Update Failed'; exit 1; } if [[ -d ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi echo -n "Downloading latest version of: $repositoryName." git clone -q "https://github.com/$githubUserName/$repositoryName" && touch .BSnippetsHiddenFile || { echo "Failure!"; exit 1; } & while [ ! -f .BSnippetsHiddenFile ]; do { echo -n "."; sleep 2; };done rm -f .BSnippetsHiddenFile echo "Success!" cd $repositoryName || { echo 'Update Failed'; exit 1; } git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit." chmod a+x install.sh #this might be necessary in your case but wasnt in mine. ./$nameOfInstallFile "update" || exit 1 cd .. rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; } else exit 1 fi else echo "$repositoryName is already the latest version" fi fi } ## This function gets 3 results similar to the item of interest getSimilar() { export PYTHONIOENCODING=utf8 #necessary for python in some cases media=$( echo "$@" | tr " " + ) response=$(httpGet "https://tastedive.com/api/similar?q=$media&k=$apiKey&info=$info") ## Extrapolate the information by parsing the JSON nameOne=$(echo "$response" |python -c "from __future__ import print_function; import sys, json; print(json.load(sys.stdin)['Similar']['Results'][0]['Name'])" 2> /dev/null || { echo "Error: Did you search a valid item?"; return 1; } ) typeOne=$(echo "$response" | python -c "from __future__ import print_function; import sys, json; print(json.load(sys.stdin)['Similar']['Results'][0]['Type'])" 2> /dev/null) nameTwo=$(echo "$response" | python -c "from __future__ import print_function; import sys, json; print(json.load(sys.stdin)['Similar']['Results'][1]['Name'])" 2> /dev/null) typeTwo=$(echo "$response" | python -c "from __future__ import print_function; import sys, json; print(json.load(sys.stdin)['Similar']['Results'][1]['Type'])" 2> /dev/null) nameThree=$(echo "$response" | python -c "from __future__ import print_function; import sys, json; print(json.load(sys.stdin)['Similar']['Results'][2]['Name'])" 2> /dev/null) typeThree=$(echo "$response" | python -c "from __future__ import print_function; import sys, json; print(json.load(sys.stdin)['Similar']['Results'][2]['Type'])" 2> /dev/null) if [[ $info == "1" ]];then ## if we want more detailed info we have to grab a few more fields wikiOne=$(echo "$response" | python -c "from __future__ import print_function; import sys, json; print(json.load(sys.stdin)['Similar']['Results'][0]['wTeaser'])" 2> /dev/null) wikiTwo=$(echo "$response" | python -c "from __future__ import print_function; import sys, json; print(json.load(sys.stdin)['Similar']['Results'][1]['wTeaser'])" 2> /dev/null) wikiThree=$(echo "$response" | python -c "from __future__ import print_function; import sys, json; print(json.load(sys.stdin)['Similar']['Results'][2]['wTeaser'])" 2> /dev/null) youtube=$(echo "$response" | python -c "from __future__ import print_function; import sys, json; print(json.load(sys.stdin)['Similar']['Results'][0]['yUrl'])" 2> /dev/null) fi } ## This function grabs all the information it can on the item of interest itself getInfo() { export PYTHONIOENCODING=utf8 #necessary for python in some cases media=$( echo "$@" | tr " " + ) response=$(httpGet "https://tastedive.com/api/similar?q=$media&k=$apiKey&info=$info") name=$(echo "$response" | python -c "from __future__ import print_function; import sys, json; print(json.load(sys.stdin)['Similar']['Info'][0]['Name'])") type=$(echo "$response" | python -c "from __future__ import print_function; import sys, json; print(json.load(sys.stdin)['Similar']['Info'][0]['Type'])") if [[ $info == "1" ]]; then wiki=$(echo "$response" | python -c "from __future__ import print_function; import sys, json; print(json.load(sys.stdin)['Similar']['Info'][0]['wTeaser'])") youtube=$(echo "$response" | python -c "from __future__ import print_function; import sys, json; print(json.load(sys.stdin)['Similar']['Info'][0]['yUrl'])") else wiki="None" youtube="None" fi } printResults() { if [[ $info == "1" ]];then echo "===================================" echo echo "$nameOne": "$typeOne" echo "$wikiOne" echo echo echo "$nameTwo": "$typeTwo" echo "$wikiTwo" echo echo echo "$nameThree": "$typeThree" echo "$wikiThree" echo if [[ $youtube != "None" ]]; then echo $youtube; fi echo echo "===================================" else echo "===================================" echo "$nameOne": "$typeOne" echo "$nameTwo": "$typeTwo" echo "$nameThree": "$typeThree" echo "===================================" fi } printInfo() { echo "===================================" echo echo "$name": "$type" echo $wiki echo if [[ $youtube != "None" ]]; then echo $youtube; fi echo "===================================" } usage() { cat <&2 exit 1 ;; h) usage exit 0 ;; v) echo "Version $currentVersion" exit 0 ;; u) checkInternet || exit 1 update exit 0 ;; i) if [[ $search == "0" ]]; then info="1" else echo "Error: the options -i and -s are mutually exclusive (-s already uses -i)" exit 1 fi ;; s) if [[ $info != "1" ]]; then search="1" info="1" else echo "Error: the options -i and -s are mutually exclusive (-s already uses -i)" exit 1 fi ;; :) echo "Option -$OPTARG requires an argument." >&2 exit 1 ;; esac done if [[ $# == 0 ]]; then usage elif [[ $1 == "update" ]]; then checkInternet || exit 1 update elif [[ $1 == "help" ]]; then usage else checkInternet || exit 1 if [[ $search == "0" ]]; then if [[ $info == "0" ]]; then getSimilar "$@" || exit 1 ## exit if we return 1 (chances are movie was not found) printResults else getSimilar "${@:2}" || exit 1 printResults fi else getInfo "${@:2}" || exit 1 ## exit if we return 1 (chances are movie was not found) printInfo fi fi ================================================ FILE: tests/bak2dvd.bats ================================================ #!/usr/bin/env bats # export TOOL_NAME='bak2dvd' setup() { # $REPO_DIR/tests/bak2dvd.bats REPO_DIR="$( cd "$( dirname "${BATS_TEST_DIRNAME}")" >/dev/null 2>&1 && pwd)" TOOL_DIR="$( cd "${REPO_DIR}/${TOOL_NAME}" >/dev/null 2>&1 && pwd)" } @test "Testing ${TOOL_NAME} tool" { echo "${TOOL_NAME}" } @test "Confirm the \$REPO_DIR variable is evaluated" { cd "${REPO_DIR}" && pwd [[ "$status" -eq 0 ]] } # can cd into script dir @test "Confirm a valid directory for ${TOOL_NAME}" { cd "${TOOL_DIR}" && pwd [[ "$status" -eq 0 ]] } @test "Check for latest version of bash-snippets on update" { if [[ "$(uname)" == "Linux" ]]; then run "${TOOL_DIR}/${TOOL_NAME}" update [[ "$status" -eq 0 ]] [ "$output" == "Bash-Snippets is already the latest version" ] fi } @test "The -h option should print usage" { run "${TOOL_DIR}/${TOOL_NAME}" -h [[ "$status" -eq 0 ]] # if bash is less than 7 yrs old if ((${BASH_VERSINFO[0]} >= 4)); then [[ "${lines[0]}" = "${TOOL_NAME^}" ]] else # or im probably a stoneage mac [[ "$(echo "${output}" | grep -i "${TOOL_NAME}")" ]] fi } @test "No arguments prints usage instructions" { run "${TOOL_DIR}/${TOOL_NAME}" [[ "$status" -eq 0 ]] # if bash is less than 7 yrs old if ((${BASH_VERSINFO[0]} >= 4)); then [[ "${lines[0]}" = "${TOOL_NAME^}" ]] else # or im probably a stoneage mac [[ "$(echo "${output}" | grep -i "${TOOL_NAME}")" ]] fi } @test "Get the tools version with -v" { run "${TOOL_DIR}/${TOOL_NAME}" -v [[ "$status" -eq 0 ]] expected='Version' [[ "${output}" =~ "${expected}" ]] } # Tool specific tests ================================================ FILE: tests/cheat.bats ================================================ #!/usr/bin/env bats export TOOL_NAME='cheat' setup() { # $REPO_DIR/tests/tool.bats REPO_DIR="$( cd "$( dirname "${BATS_TEST_DIRNAME}")" >/dev/null 2>&1 && pwd)" TOOL_DIR="$( cd "${REPO_DIR}/${TOOL_NAME}" >/dev/null 2>&1 && pwd)" } @test "Testing ${TOOL_NAME} tool" { echo "${TOOL_NAME}" } @test "Confirm the \$REPO_DIR variable is evaluated" { cd "${REPO_DIR}" && pwd [[ "$status" -eq 0 ]] } # can cd into script dir @test "Confirm a valid directory for ${TOOL_NAME}" { cd "${TOOL_DIR}" && pwd [[ "$status" -eq 0 ]] } @test "Check for latest version of bash-snippets on update" { if [[ "$(uname)" == "Linux" ]]; then run "${TOOL_DIR}/${TOOL_NAME}" update [[ "$status" -eq 0 ]] [ "$output" == "Bash-Snippets is already the latest version" ] fi } @test "The -h option should print usage" { run "${TOOL_DIR}/${TOOL_NAME}" -h [[ "$status" -eq 0 ]] # if bash is less than 7 yrs old if ((${BASH_VERSINFO[0]} >= 4)); then [[ "${lines[0]}" = "${TOOL_NAME^}" ]] else # or im probably a stoneage mac [[ "$(echo "${output}" | grep -i "${TOOL_NAME}")" ]] fi } @test "No arguments prints usage instructions" { run "${TOOL_DIR}/${TOOL_NAME}" [[ "$status" -eq 0 ]] # if bash is less than 7 yrs old if ((${BASH_VERSINFO[0]} >= 4)); then [[ "${lines[0]}" = "${TOOL_NAME^}" ]] else # or im probably a stoneage mac [[ "$(echo "${output}" | grep -i "${TOOL_NAME}")" ]] fi } @test "Get the tools version with -v" { run "${TOOL_DIR}/${TOOL_NAME}" -v [[ "$status" -eq 0 ]] expected='Version' [[ "${output}" =~ "${expected}" ]] } @test "Grabbing information on a programming language (rust)" { run "${TOOL_DIR}/${TOOL_NAME}" rust [[ "$status" -eq 0 ]] [[ "${lines[0]}" =~ 'Rust is a systems' ]] } @test "Testing unkown topic due to misspelling" { run "${TOOL_DIR}/${TOOL_NAME}" suuuper thiingsa [[ "$status" -eq 0 ]] [[ "printf '%s\n' ${lines[1]}" =~ 'Unknown' ]] } ================================================ FILE: tests/cloudup.bats ================================================ #!/usr/bin/env bats @test "Testing cloudup tool" { echo cloudup } @test "Check for latest version of bash-snippets on update" { if [[ "$(uname)" == "Linux" ]];then run cloudup update [ "$status" -eq 0 ] [ "$output" = "Bash-Snippets is already the latest version" ] fi } @test "The -h option should print usage" { run cloudup -h [ "$status" -eq 0 ] [ "${lines[0]}" = "Cloudup" ] } @test "Get the tools version with -v" { run cloudup -v [ "$status" -eq 0 ] result=$( echo $(cloudup -v) | grep -Eo "Version") [ "$result" = "Version" ] } ================================================ FILE: tests/crypt.bats ================================================ #!/usr/bin/env bats @test "Testing crypt tool" { echo crypt } @test "Check for latest version of bash-snippets on update" { if [[ "$(uname)" == "Linux" ]];then run crypt update [ "$status" -eq 0 ] [ "$output" = "Bash-Snippets is already the latest version" ] fi } @test "The -h option should print usage" { run crypt -h [ "$status" -eq 0 ] [ "${lines[0]}" = "Crypt" ] } @test "No arguments prints usage instructions" { run crypt [ "$status" -eq 0 ] [ "${lines[0]}" = "Crypt" ] } @test "Get the tools version with -v" { run crypt -v [ "$status" -eq 0 ] result=$( echo $(crypt -v) | grep -Eo "Version") [ "$result" = "Version" ] } ================================================ FILE: tests/cryptocurrency.bats ================================================ #!/usr/bin/env bats @test "Testing cryptocurrency tool" { echo cryptocurrency } @test "Check for latest version of bash-snippets on update" { if [[ "$(uname)" == "Linux" ]];then run cryptocurrency update [ "$status" -eq 0 ] [ "$output" = "Bash-Snippets is already the latest version" ] fi } @test "The -h option should print usage" { run cryptocurrency -h [ "$status" -eq 0 ] [ "${lines[0]}" = "CryptoCurrency" ] } @test "Get the tools version with -v" { run cryptocurrency -v [ "$status" -eq 0 ] result=$( echo $(cryptocurrency -v) | grep -Eo "Version") [ "$result" = "Version" ] } ================================================ FILE: tests/currency.bats ================================================ #!/usr/bin/env bats @test "Testing currency tool" { echo currency } @test "Check for latest version of bash-snippets on update" { if [[ "$(uname)" == "Linux" ]];then run currency update [ "$status" -eq 0 ] [ "$output" = "Bash-Snippets is already the latest version" ] fi } @test "The -h option should print usage" { run currency -h [ "$status" -eq 0 ] [ "${lines[0]}" = "Currency" ] } @test "Testing currency exchange (12.35 EUR TO USD)" { run currency EUR USD 12.35 [ "$status" -eq 0 ] ##[ "${lines[0]}" = "=========================" ] ##[ "${lines[1]}" = "| EUR to USD" ] ##[ "${lines[3]}" = "| EUR: 12.35" ] } @test "Get the tools version with -v" { run currency -v [ "$status" -eq 0 ] result=$( echo $(currency -v) | grep -Eo "Version") [ "$result" = "Version" ] } ================================================ FILE: tests/geo.bats ================================================ #!/usr/bin/env bats @test "Testing geo tool" { echo geo } @test "Check for latest version of bash-snippets on update" { if [[ "$(uname)" == "Linux" ]];then run geo update [ "$status" -eq 0 ] [ "$output" = "Bash-Snippets is already the latest version" ] fi } @test "The -h option should print usage" { run geo -h [ "$status" -eq 0 ] [ "${lines[0]}" = "Geo" ] } @test "Get the tools version with -v" { run geo -v [ "$status" -eq 0 ] result=$( echo $(geo -v) | grep -Eo "Version") [ "$result" = "Version" ] } ================================================ FILE: tests/gist.bats ================================================ #!/usr/bin/env bats export TOOL_NAME='gist' export GIST_USER='phamhsieh' export GIST_API_TOKEN='dd43dc9949a5b4a1d6c7''b779f13af357282016e4' setup() { # $REPO_DIR/tests/taste.bats REPO_DIR="$( cd "$( dirname "${BATS_TEST_DIRNAME}")" >/dev/null 2>&1 && pwd)" TOOL_DIR="$( cd "${REPO_DIR}/${TOOL_NAME}" >/dev/null 2>&1 && pwd)" } @test "Testing ${TOOL_NAME} tool" { echo "${TOOL_NAME}" } @test "Get the tools version with command version" { run "${TOOL_DIR}/${TOOL_NAME}" version [ "$status" -eq 0 ] result=$( echo $(${TOOL_DIR}/${TOOL_NAME} version) | grep -Eo "Version") [ "$result" = "Version" ] } @test "Check for latest version of bash-snippets on update" { if [[ "$(uname)" == "Linux" ]]; then run "${TOOL_DIR}/${TOOL_NAME}" update [[ "$status" -eq 0 ]] [ "$output" == "Bash-Snippets is already the latest version" ] fi } @test "The help command should print usage" { run "${TOOL_DIR}/${TOOL_NAME}" help [[ "$status" -eq 0 ]] [[ "${lines[0]}" = "${TOOL_NAME}" ]] } @test "Use config command to add configuarion for user" { run "${TOOL_DIR}/${TOOL_NAME}" config user ${GIST_USER} [ "$status" -eq 0 ] [ "${lines[-1]}" = "user=${GIST_USER}" ] } @test "Use config command to add configuarion for token" { run "${TOOL_DIR}/${TOOL_NAME}" config token ${GIST_API_TOKEN} [ "$status" -eq 0 ] [ "${lines[-1]}" = "token=${GIST_API_TOKEN}" ] } @test "The new command should create a new public gist with gist command" { hint=false run "${TOOL_DIR}/${TOOL_NAME}" new --file gist --desc 'Manage gist like a pro' "${TOOL_DIR}/${TOOL_NAME}" [ "$status" -eq 0 ] [[ "${lines[-1]}" =~ ([0-9]+ +https://gist.github.com/[0-9a-z]+) ]] } @test "The fetch command should fetch user gists" { hint=false run "${TOOL_DIR}/${TOOL_NAME}" fetch [ "$status" -eq 0 ] [[ "${lines[-1]}" =~ ([0-9]+ +https://gist.github.com/[0-9a-z]+) ]] } @test "The fetch command should fetch starred gists" { hint=false run "${TOOL_DIR}/${TOOL_NAME}" fetch star [ "$status" -eq 0 ] echo ${lines[-1]} [[ "${lines[-1]}" =~ (Not a single valid gist|^ *s[0-9]+ +https://gist.github.com/[0-9a-z]+) ]] } @test "No arguments prints the list of gists" { hint=false run "${TOOL_DIR}/${TOOL_NAME}" [ "$status" -eq 0 ] [[ "${lines[-1]}" =~ ([0-9]+ +https://gist.github.com/[0-9a-z]+) ]] } @test "Specify an index to return the path of cloned repo" { run "${TOOL_DIR}/${TOOL_NAME}" 1 --no-action [ "$status" -eq 0 ] [[ "${lines[-1]}" =~ (${HOME}/gist/[0-9a-z]+) ]] } @test "The edit command should modify the description of a gist" { "${TOOL_DIR}/${TOOL_NAME}" edit 1 "Modified description" run "${TOOL_DIR}/${TOOL_NAME}" detail 1 [ "$status" -eq 0 ] [[ "${lines[0]}" =~ (Modified description$) ]] } @test "The delete command should delete specified gists" { run "${TOOL_DIR}/${TOOL_NAME}" delete 1 --force [ "$status" -eq 0 ] [ "${lines[0]}" = '1 deleted' ] } @test "The user command should get the list of public gists from a user" { run "${TOOL_DIR}/${TOOL_NAME}" user defunkt [ "$status" -eq 0 ] [[ "${lines[0]}" =~ (https://gist.github.com/[0-9a-z]+ defunkt) ]] } ================================================ FILE: tests/meme.bats ================================================ #!/usr/bin/env bats @test "Testing meme tool" { echo meme } @test "Check for latest version of bash-snippets on update" { if [[ "$(uname)" == "Linux" ]];then run meme update [ "$status" -eq 0 ] [ "$output" = "Bash-Snippets is already the latest version" ] fi } @test "The -h option should print usage" { run meme -h [ "$status" -eq 0 ] [ "${lines[0]}" = "Meme" ] } @test "Get the tools version with -v" { run meme -v [ "$status" -eq 0 ] result=$( echo $(meme -v) | grep -Eo "Version") [ "$result" = "Version" ] } ================================================ FILE: tests/movies.bats ================================================ #!/usr/bin/env bats @test "Testing movies tool" { echo movies } @test "Check for latest version of bash-snippets on update" { if [[ "$(uname)" == "Linux" ]];then run movies update [ "$status" -eq 0 ] [ "$output" = "Bash-Snippets is already the latest version" ] fi } @test "The -h option should print usage" { run movies -h [ "$status" -eq 0 ] [ "${lines[0]}" = "Movies" ] } @test "No arguments prints usage instructions" { run movies [ "$status" -eq 0 ] [ "${lines[0]}" = "Movies" ] } @test "Get information on a single movie" { run movies Argo [ "$status" -eq 0 ] [ "${lines[0]}" = "+=====================================================+" ] [ "${lines[1]}" = "| Title: Argo |" ] } @test "Get the tools version with -v" { run movies -v [ "$status" -eq 0 ] result=$( echo $(movies -v) | grep -Eo "Version") [ "$result" = "Version" ] } ================================================ FILE: tests/newton.bats ================================================ #!/usr/bin/env bats @test "Testing newton tool" { echo newton } @test "Check for latest version of bash-snippets on update" { if [[ "$(uname)" == "Linux" ]];then run newton update [ "$status" -eq 0 ] [ "$output" = "Bash-Snippets is already the latest version" ] fi } @test "The -h option should print usage" { run newton -h [ "$status" -eq 0 ] [ "${lines[0]}" = "Newton" ] } @test "Testing newton simplify for [[2x^2]+7]*[4x^2]" { run newton simplify [[2x^2]+7]*[4x^2] [ "$status" -eq 0 ] [ "${lines[0]}" = "================================" ] if [ $(uname) == "Linux" ];then [ "${lines[3]}" = "|Result: 8 x^4 + 28 x^2" ] ## this works for darwin but the test wont fi } @test "Testing newton bad characters in expression " { run newton simplify 3x= [ "$status" -eq 1 ] [ "${lines[0]}" = "Error: Expression contains invalid characters" ] } @test "Testing newton bad operation " { run newton jokes 2x^2 [ "$status" -eq 1 ] [ "${lines[0]}" = "Error: invalid operation, run newton -h to get a list of valid operations" ] } @test "Get the tools version with -v" { run newton -v [ "$status" -eq 0 ] result=$( echo $(newton -v) | grep -Eo "Version") [ "$result" = "Version" ] } ================================================ FILE: tests/qrify.bats ================================================ #!/usr/bin/env bats @test "Testing qrify tool" { echo qrify } @test "Check for latest version of bash-snippets on update" { if [[ "$(uname)" == "Linux" ]];then run qrify update [ "$status" -eq 0 ] [ "$output" = "Bash-Snippets is already the latest version" ] fi } @test "The -h option should print usage" { run qrify -h [ "$status" -eq 0 ] [ "${lines[0]}" = "Qrify" ] } @test "Getting the qr code for a test string" { run qrify this is a test string [ "$status" -eq 0 ] [ "${lines[0]}" = "█████████████████████████████████" ] [ "${lines[1]}" = "█████████████████████████████████" ] [ "${lines[2]}" = "████ ▄▄▄▄▄ ██▀▄████ ██ ▄▄▄▄▄ ████" ] [ "${lines[3]}" = "████ █ █ █▄▀█▄▀█ ▀▀█ █ █ ████" ] [ "${lines[4]}" = "████ █▄▄▄█ ██▄▀▀ ▄ ▀█ █▄▄▄█ ████" ] } @test "No arguments prints usage instructions" { run qrify [ "$status" -eq 0 ] [ "${lines[0]}" = "Qrify" ] } @test "Get the tools version with -v" { run qrify -v [ "$status" -eq 0 ] result=$( echo $(qrify -v) | grep -Eo "Version") [ "$result" = "Version" ] } ================================================ FILE: tests/short.bats ================================================ #!/usr/bin/env bats export TOOL_NAME='short' setup() { # $REPO_DIR/tests/short.bats REPO_DIR="$( cd "$( dirname "${BATS_TEST_DIRNAME}")" >/dev/null 2>&1 && pwd)" TOOL_DIR="$( cd "${REPO_DIR}/${TOOL_NAME}" >/dev/null 2>&1 && pwd)" } @test "Testing ${TOOL_NAME} tool" { echo "${TOOL_NAME}" } @test "Confirm the \$REPO_DIR variable is evaluated" { cd "${REPO_DIR}" && pwd [[ "$status" -eq 0 ]] } # can cd into script dir @test "Confirm a valid directory for ${TOOL_NAME}" { cd "${TOOL_DIR}" && pwd [[ "$status" -eq 0 ]] } @test "Check for latest version of bash-snippets on update" { if [[ "$(uname)" == "Linux" ]]; then run "${TOOL_DIR}/${TOOL_NAME}" update [[ "$status" -eq 0 ]] [ "$output" == "Bash-Snippets is already the latest version" ] fi } @test "The -h option should print usage" { run "${TOOL_DIR}/${TOOL_NAME}" -h [[ "$status" -eq 0 ]] # if bash is less than 7 yrs old if ((${BASH_VERSINFO[0]} >= 4)); then [[ "${lines[0]}" = "${TOOL_NAME^}" ]] else # or im probably a stoneage mac [[ "$(echo "${output}" | grep -i "${TOOL_NAME}")" ]] fi } @test "No arguments prints usage instructions" { run "${TOOL_DIR}/${TOOL_NAME}" [[ "$status" -eq 0 ]] # if bash is less than 7 yrs old if ((${BASH_VERSINFO[0]} >= 4)); then [[ "${lines[0]}" = "${TOOL_NAME^}" ]] else # or im probably a stoneage mac [[ "$(echo "${output}" | grep -i "${TOOL_NAME}")" ]] fi } @test "Get the tools version with -v" { run "${TOOL_DIR}/${TOOL_NAME}" -v [[ "$status" -eq 0 ]] expected='Version' [[ "${output}" =~ "${expected}" ]] } # Tool specific tests @test "Shorten github repo URL" { longurl='https://github.com/alexanderepstein/Bash-Snippets' run "${TOOL_DIR}/${TOOL_NAME}" -s "${longurl}" [[ "$status" -eq 0 ]] expected='http://tinyurl.com/.+' [[ "${lines[2]}" =~ (${expected}) ]] } @test "Expand tinyurl URL" { shorturl='http://tinyurl.com/uowfbb5' run "${TOOL_DIR}/${TOOL_NAME}" -e "${shorturl}" [[ "$status" -eq 0 ]] expected='https://github.com/alexanderepstein/Bash-Snippets' [[ "${lines[2]}" =~ "${expected}" ]] } ================================================ FILE: tests/siteciphers.bats ================================================ #!/usr/bin/env bats @test "Testing siteciphers tool" { echo siteciphers } @test "Check for latest version of bash-snippets on update" { if [[ "$(uname)" == "Linux" ]];then run siteciphers update [ "$status" -eq 0 ] [ "$output" = "Bash-Snippets is already the latest version" ] fi } @test "No arguments prints usage instructions" { run siteciphers [ "$status" -eq 1 ] [ "${lines[0]}" = "Siteciphers" ] } @test "The -h option should print usage" { run siteciphers -h [ "$status" -eq 0 ] [ "${lines[0]}" = "Siteciphers" ] } #@test "Running siteciphers on travis-ci" { # run siteciphers travis-ci.org # [ "$status" -eq 0 ] # [ "${lines[0]}" = "ECDHE-RSA-AES256-GCM-SHA384 - NO (tlsv1 alert insufficient security)" ] #} @test "Get the tools version with -v" { run siteciphers -v [ "$status" -eq 0 ] result=$( echo $(siteciphers -v) | grep -Eo "Version") [ "$result" = "Version" ] } ================================================ FILE: tests/stocks.bats ================================================ #!/usr/bin/env bats @test "Testing stocks tool" { echo stocks } @test "Check for latest version of bash-snippets on update" { if [[ "$(uname)" == "Linux" ]];then run stocks update [ "$status" -eq 0 ] [ "$output" = "Bash-Snippets is already the latest version" ] fi } @test "The -h option should print usage" { run stocks -h [ "$status" -eq 0 ] [ "${lines[0]}" = "Stocks" ] } @test "No arguments prints usage instructions" { run stocks [ "$status" -eq 0 ] [ "${lines[0]}" = "Stocks" ] } @test "Get stock info by passing in ticker" { result=$( echo $(stocks AAPL) | grep -Eo "Apple Inc. -- Stock Information" ) [ "$result" = "Apple Inc. -- Stock Information" ] } @test "Get stock info by passing in company" { result=$( echo $(stocks Apple) | grep -Eo "Apple Inc. -- Stock Information" ) [ "$result" = "Apple Inc. -- Stock Information" ] } @test "Get the tools version with -v" { run stocks -v [ "$status" -eq 0 ] result=$( echo $(stocks -v) | grep -Eo "Version") [ "$result" = "Version" ] } ================================================ FILE: tests/taste.bats ================================================ #!/usr/bin/env bats export TOOL_NAME='taste' export TASTE_API_KEY="290044-Taste-QIQUQKOZ" setup() { # $REPO_DIR/tests/taste.bats REPO_DIR="$( cd "$( dirname "${BATS_TEST_DIRNAME}")" >/dev/null 2>&1 && pwd)" TOOL_DIR="$( cd "${REPO_DIR}/${TOOL_NAME}" >/dev/null 2>&1 && pwd)" } @test "Testing ${TOOL_NAME} tool" { echo "${TOOL_NAME}" } @test "Check for latest version of bash-snippets on update" { if [[ "$(uname)" == "Linux" ]]; then run "${TOOL_DIR}/${TOOL_NAME}" update [[ "$status" -eq 0 ]] [ "$output" == "Bash-Snippets is already the latest version" ] fi } @test "The -h option should print usage" { run "${TOOL_DIR}/${TOOL_NAME}" -h [[ "$status" -eq 0 ]] # if bash is less than 7 yrs old if ((${BASH_VERSINFO[0]} >= 4)); then [[ "${lines[0]}" = "${TOOL_NAME^}" ]] else # or im probably a stoneage mac [[ "$(echo "${output}" | grep -i "${TOOL_NAME}")" ]] fi } @test "No arguments prints usage instructions" { run "${TOOL_DIR}/${TOOL_NAME}" [[ "$status" -eq 0 ]] # if bash is less than 7 yrs old if ((${BASH_VERSINFO[0]} >= 4)); then [[ "${lines[0]}" = "${TOOL_NAME^}" ]] else # or im probably a stoneage mac [[ "$(echo "${output}" | grep -i "${TOOL_NAME}")" ]] fi } @test "Get the tools version with -v" { run "${TOOL_DIR}/${TOOL_NAME}" -v [[ "$status" -eq 0 ]] expected='Version' [[ "${output}" =~ "${expected}" ]] } @test "Testing short recommendations" { run "${TOOL_DIR}/${TOOL_NAME}" 50 Cent # order of ouput lines changed [[ "$status" -eq 0 ]] expected='(G-Unit|The Game|Lloyd Banks): .+' [ "${lines[0]}" = "===================================" ] [[ "${lines[1]}" =~ ${expected} ]] [[ "${lines[2]}" =~ ${expected} ]] [[ "${lines[3]}" =~ ${expected} ]] [ "${lines[4]}" = "===================================" ] } @test "Testing long recommendations" { run "${TOOL_DIR}/${TOOL_NAME}" -i Sublime [[ "$status" -eq 0 ]] expected='Soundsystem is the fifth studio album by 311, released on October 12, 1999. Soundsystem, which was certified Gold by the RIAA,' [[ "${output}" =~ "${expected}" ]] } @test "Testing search on item" { run "${TOOL_DIR}/${TOOL_NAME}" -s Kendrick Lamar [[ "$status" -eq 0 ]] expected='Kendrick Lamar Duckworth' [[ "${output}" =~ "${expected}" ]] } ================================================ FILE: tests/todo.bats ================================================ #!/usr/bin/env bats @test "Testing todo tool" { echo todo } @test "Check for latest version of bash-snippets on update" { if [[ "$(uname)" == "Linux" ]];then run todo update [ "$status" -eq 0 ] [ "$output" = "Bash-Snippets is already the latest version" ] fi } @test "No arguments prints usage instructions" { run todo [ "$status" -eq 0 ] [ "${lines[0]}" = "Todo" ] } @test "The -h option should print usage" { run todo -h [ "$status" -eq 0 ] [ "${lines[0]}" = "Todo" ] } @test "Adding task" { run todo -a First task ever [ "$status" -eq 0 ] result=$( echo $(todo -g) | grep -Eo "01\). First task ever" ) [ "$result" = "01). First task ever" ] } @test "Getting task" { run todo -g [ "$status" -eq 0 ] result=$( echo $(todo -g) | grep -Eo "01\). First task ever" ) [ "$result" = "01). First task ever" ] } @test "Removing task" { run todo -r "1" [ "$status" -eq 0 ] result=$( cat ~/.todo/list.txt ) echo $result [ "$result" = "" ] } @test "Getting from empty task list" { run todo -g [ "$status" -eq 0 ] [ "$output" = "No tasks found" ] } @test "Get the tools version with -v" { run todo -v [ "$status" -eq 0 ] result=$( echo $(todo -v) | grep -Eo "Version") [ "$result" = "Version" ] } ================================================ FILE: tests/transfer.bats ================================================ #!/usr/bin/env bats @test "Testing transfer tool" { echo transfer } @test "Check for latest version of bash-snippets on update" { if [[ "$(uname)" == "Linux" ]];then run transfer update [ "$status" -eq 0 ] [ "$output" = "Bash-Snippets is already the latest version" ] fi } @test "The -h option should print usage" { run transfer -h [ "$status" -eq 0 ] [ "${lines[0]}" = "Transfer" ] } @test "Testing file upload" { touch $HOME/testFile.txt echo -n "This is some example content." > $HOME/testFile.txt run transfer $HOME/testFile.txt transferResponse=$(transfer $HOME/testFile.txt) rm -f $HOME/testFile.txt transferCommand=$( echo $transferResponse | cut -d $'\n' -f 3 | sed s/"Transfer Download Command:"//g | sed s:"desiredOutputDirectory":"$HOME":g | sed s:"^ "::g) transferStatus=$( echo $transferResponse | grep -Eo "Success!") [ "$status" -eq 0 ] [ "$transferStatus" = "Success!" ] ## this works for darwin but the test wont } #@test "Testing file upload & download" { #touch $HOME/testFile.txt #echo -n "This is some example content." > $HOME/testFile.txt #ransferResponse=$(transfer $HOME/testFile.txt) #transferCommand=$( echo $transferResponse | cut -d $'\n' -f 3 | sed s/"Transfer Download Command:"//g | sed s:"desiredOutputDirectory":"$HOME":g | sed s:"^ "::g) #id=$(echo $transferResponse | cut -d "/" -f 4) #transferStatus=$( echo $transferResponse | grep -Eo "Success!") #[ "$transferStatus" = "Success!" ] #rm -f $HOME/testFile.txt #if [ -f $HOME/testFile.txt ];then exit 1;fi #run transfer -d $HOME $id testFile.txt #if [ ! -f $HOME/testFile.txt ];then exit 1;fi #contents=$(cat $HOME/testFile.txt) #if [ $contents != "This is some example content." ];then exit 1; fi #rm -f $HOME/testFile.txt #transferResponse=$(transfer -d $HOME $id testFile.txt) #transferStatus=$( echo $transferResponse | grep -Eo "Success!") #[ "$transferStatus" = "Success!" ] #rm -f $HOME/testFile.txt #} @test "Get the tools version with -v" { run transfer -v [ "$status" -eq 0 ] result=$( echo $(transfer -v) | grep -Eo "Version") [ "$result" = "Version" ] } ================================================ FILE: tests/weather.bats ================================================ #!/usr/bin/env bats export TOOL_NAME='weather' setup() { # $REPO_DIR/tests/weather.bats REPO_DIR="$( cd "$( dirname "${BATS_TEST_DIRNAME}")" >/dev/null 2>&1 && pwd)" TOOL_DIR="$( cd "${REPO_DIR}/${TOOL_NAME}" >/dev/null 2>&1 && pwd)" } @test "Testing ${TOOL_NAME} tool" { echo "${TOOL_NAME}" } @test "Confirm the \$REPO_DIR variable is evaluated" { cd "${REPO_DIR}" && pwd [[ "$status" -eq 0 ]] } # can cd into script dir @test "Confirm a valid directory for ${TOOL_NAME}" { cd "${TOOL_DIR}" && pwd [[ "$status" -eq 0 ]] } @test "Check for latest version of bash-snippets on update" { if [[ "$(uname)" == "Linux" ]]; then run "${TOOL_DIR}/${TOOL_NAME}" update [[ "$status" -eq 0 ]] [ "$output" == "Bash-Snippets is already the latest version" ] fi } @test "The -h option should print usage" { run "${TOOL_DIR}/${TOOL_NAME}" -h [[ "$status" -eq 0 ]] # if bash is less than 7 yrs old if ((${BASH_VERSINFO[0]} >= 4)); then [[ "${lines[0]}" = "${TOOL_NAME^}" ]] else # or im probably a stoneage mac [[ "$(echo "${output}" | grep -i "${TOOL_NAME}")" ]] fi } @test "No arguments shows weather at current location" { run "${TOOL_DIR}/${TOOL_NAME}" [[ "$status" -eq 0 ]] expected='Weather report: .+' [[ "${lines[0]}" =~ ${expected} ]] } @test "Get the tools version with -v" { run "${TOOL_DIR}/${TOOL_NAME}" -v [[ "$status" -eq 0 ]] expected='Version' [[ "${output}" =~ "${expected}" ]] } # Tool specific tests @test "Testing weather with specified location" { run "${TOOL_DIR}/${TOOL_NAME}" Paramus [ "$status" -eq 0 ] # API changed #[ "${lines[0]}" = "Weather report: Paramus, United States of America" ] [ "${lines[0]}" = "Weather report: Paramus" ] } ================================================ FILE: tests/ytview.bats ================================================ #!/usr/bin/env bats @test "Testing ytview tool" { echo ytview } @test "Check for latest version of bash-snippets on update" { if [[ "$(uname)" == "Linux" ]];then run ytview update [ "$output" = "Bash-Snippets is already the latest version" ] fi } @test "The -h option should print usage" { run ytview -h [ "${lines[0]}" = "Ytview" ] } @test "No arguments prints usage instructions" { run ytview [ "$status" -eq 0 ] [ "${lines[0]}" = "Ytview" ] } @test "Get the tools version with -v" { result=$( echo $(ytview -v) | grep -Eo "Version") [ "$result" = "Version" ] } ================================================ FILE: todo/todo ================================================ #!/usr/bin/env bash # Author: Alexander Epstein https://github.com/alexanderepstein flag="" currentVersion="1.23.0" configuredClient="" ## This function determines which http get tool the system has installed and returns an error if there isnt one getConfiguredClient() { if command -v curl &>/dev/null; then configuredClient="curl" elif command -v wget &>/dev/null; then configuredClient="wget" elif command -v http &>/dev/null; then configuredClient="httpie" elif command -v fetch &>/dev/null; then configuredClient="fetch" else echo "Error: This tool requires either curl, wget, httpie or fetch to be installed." >&2 return 1 fi } ## Allows to call the users configured client without if statements everywhere httpGet() { case "$configuredClient" in curl) curl -A curl -s "$@" ;; wget) wget -qO- "$@" ;; httpie) http -b GET "$@" ;; fetch) fetch -q "$@" ;; esac } update() { # Author: Alexander Epstein https://github.com/alexanderepstein # Update utility version 2.2.0 # To test the tool enter in the defualt values that are in the examples for each variable repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then echo "Error: update utility has not been configured correctly." >&2 exit 1 elif [[ $latestVersion == "" ]]; then echo "Error: no active internet connection" >&2 exit 1 else if [[ "$latestVersion" != "$currentVersion" ]]; then echo "Version $latestVersion available" echo -n "Do you wish to update $repositoryName [Y/n]: " read -r answer if [[ "$answer" == [Yy] ]]; then cd ~ || { echo 'Update Failed'; exit 1; } if [[ -d ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi echo -n "Downloading latest version of: $repositoryName." git clone -q "https://github.com/$githubUserName/$repositoryName" && touch .BSnippetsHiddenFile || { echo "Failure!"; exit 1; } & while [ ! -f .BSnippetsHiddenFile ]; do { echo -n "."; sleep 2; };done rm -f .BSnippetsHiddenFile echo "Success!" cd $repositoryName || { echo 'Update Failed'; exit 1; } git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit." chmod a+x install.sh #this might be necessary in your case but wasnt in mine. ./$nameOfInstallFile "update" || exit 1 cd .. rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; } else exit 1 fi else echo "$repositoryName is already the latest version" fi fi } addTask() { if [ ! -f ~/.todo/list.txt ]; then if [ ! -d ~/.todo ]; then mkdir ~/.todo; fi touch ~/.todo/list.txt fi echo "$1 ; $(date)" >> ~/.todo/list.txt } checkInternet() { httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request } removeTask() { ## Check for valid task numbers (valid characters) if [ -f ~/.todo/temp.txt ];then rm -f ~/.todo/temp.txt;fi touch ~/.todo/temp.txt for taskToRemove in "$@";do oldTaskNumber=$taskToRemove taskNumber=$( echo "$taskToRemove" | grep -Eo "[0-9]*" ) if [[ $taskNumber == "" || $oldTaskNumber != $taskNumber ]]; then echo "Error: $oldTaskNumber is not a valid task number!" && return 1; fi done count="0" IFS=$'\n' # make newlines the only separator ## Removing the task (only don't add to temp if we should remove it) for task in $(cat ~/.todo/list.txt); do removeIt="false" for taskToRemove in "$@";do if [[ $(($count + 1)) == "$taskToRemove" ]]; then removeIt="true" break fi done if ! $removeIt ;then echo "$task" >> ~/.todo/temp.txt;fi count=$(( $count + 1 )) done rm -f ~/.todo/list.txt cp ~/.todo/temp.txt ~/.todo/list.txt rm -f ~/.todo/temp.txt ##Checking if the task exists for taskToRemove in "$@" ;do if [ $count -lt "$taskToRemove" ]; then echo "Error: task number $taskToRemove does not exist!" else echo "Sucessfully removed task number $taskToRemove" fi done } getTasks() { if [ -f ~/.todo/list.txt ]; then checkEmpty=$(cat ~/.todo/list.txt) if [[ $checkEmpty == "" ]]; then echo "No tasks found" else count="1" IFS=$'\n' # make newlines the only separator for task in $(cat ~/.todo/list.txt); do tempTask=$count if [ $count -lt 10 ]; then tempTask="0$count"; fi echo "$tempTask). $task" >> ~/.todo/getTemp.txt count=$(( $count + 1 )) done cat ~/.todo/getTemp.txt | column -t -s ";" rm -f ~/.todo/getTemp.txt fi else echo "No tasks found" fi } usage() { cat <&2 exit 1 ;; c) if [[ $flag == "" ]]; then flag="clear" else echo "Error: all flags are mutually exclusive" exit 1 fi ;; h) usage exit 0 ;; v) echo "Version $currentVersion" exit 0 ;; g) if [[ $flag == "" ]]; then flag="get" else echo "Error: all flags are mutually exclusive" exit 1 fi ;; r) if [[ $flag == "" ]]; then flag="remove" else echo "Error: all flags are mutually exclusive" exit 1 fi ;; a) if [[ $flag == "" ]]; then flag="add" else echo "Error: all flags are mutually exclusive" exit 1 fi ;; u) getConfiguredClient || exit 1 checkInternet || exit 1 update exit 0 ;; :) echo "Option -$OPTARG requires an argument." >&2 exit 1 ;; esac done if [[ $# == "0" ]]; then usage elif [[ $# == "1" ]]; then if [[ $1 == "clear" ]]; then clearAllTasks || exit 1 elif [[ $1 == "update" ]]; then getConfiguredClient || exit 1 checkInternet || exit 1 update || exit 1 exit 0 elif [[ $1 == "help" ]]; then usage exit 0 elif [[ $flag == "clear" || $1 == "clear" ]]; then clearAllTasks || exit 1 elif [[ $flag == "get" || $1 == "list" || $1 == "get" ]]; then getTasks || exit 1 else { echo "Error: the argument $1 is not valid"; exit 1; }; fi else if [[ $flag == "add" || $1 == "add" ]]; then addTask "${*:2}" && getTasks || exit 1 elif [[ $flag == "remove" || $1 == "remove" ]]; then removeTask "${*:2}" && getTasks || exit 1 else { usage; exit 1; }; fi fi ================================================ FILE: transfer/transfer ================================================ #!/usr/bin/env bash # Author: Alexander Epstein https://github.com/alexanderepstein configuredDownloadClient="" configuredUploadClient="" configuredClient="" currentVersion="1.23.0" down="false" ## This function determines which http get tool the system has installed and returns an error if there isnt one getConfiguredDownloadClient() { if command -v curl &>/dev/null; then configuredDownloadClient="curl" elif command -v wget &>/dev/null; then configuredDownloadClient="wget" elif command -v fetch &>/dev/null; then configuredDownloadClient="fetch" else echo "Error: Downloading with this tool requires either curl, wget, or fetch to be installed." >&2 return 1 fi } ## Allows to call the users configured client without if statements everywhere httpGet() { case "$configuredClient" in curl) curl -A curl -s "$@" ;; wget) wget -qO- "$@" ;; httpie) http -b GET "$@" ;; fetch) fetch -q "$@" ;; esac } ## This function determines which http get tool the system has installed and returns an error if there isnt one getConfiguredClient() { if command -v curl &>/dev/null; then configuredClient="curl" elif command -v wget &>/dev/null; then configuredClient="wget" elif command -v http &>/dev/null; then configuredClient="httpie" elif command -v fetch &>/dev/null; then configuredClient="fetch" else echo "Error: This tool requires either curl, wget, httpie or fetch to be installed." >&2 return 1 fi } ## This function determines which http get tool the system has installed and returns an error if there isnt one getconfiguredUploadClient() { if command -v curl &>/dev/null; then configuredUploadClient="curl" elif command -v wget &>/dev/null; then configuredUploadClient="wget" else echo "Error: Uploading with this tool requires either curl or wget to be installed." >&2 return 1 fi } update() { # Author: Alexander Epstein https://github.com/alexanderepstein # Update utility version 2.2.0 # To test the tool enter in the defualt values that are in the examples for each variable repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then echo "Error: update utility has not been configured correctly." >&2 exit 1 elif [[ $latestVersion == "" ]]; then echo "Error: no active internet connection" >&2 exit 1 else if [[ "$latestVersion" != "$currentVersion" ]]; then echo "Version $latestVersion available" echo -n "Do you wish to update $repositoryName [Y/n]: " read -r answer if [[ "$answer" == [Yy] ]]; then cd ~ || { echo 'Update Failed'; exit 1; } if [[ -d ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi echo -n "Downloading latest version of: $repositoryName." git clone -q "https://github.com/$githubUserName/$repositoryName" && touch .BSnippetsHiddenFile || { echo "Failure!"; exit 1; } & while [ ! -f .BSnippetsHiddenFile ]; do { echo -n "."; sleep 2; };done rm -f .BSnippetsHiddenFile echo "Success!" cd $repositoryName || { echo 'Update Failed'; exit 1; } git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit." chmod a+x install.sh #this might be necessary in your case but wasnt in mine. ./$nameOfInstallFile "update" || exit 1 cd .. rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; } else exit 1 fi else echo "$repositoryName is already the latest version" fi fi } checkInternet() { httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request } singleUpload() { filePath=$(echo "$1" | sed s:"~":"$HOME":g) if [ ! -f "$filePath" ];then { echo "Error: invalid file path"; return 1;}; fi tempFileName=$(echo "$1" | sed "s/.*\///") echo "Uploading $tempFileName" httpSingleUpload "$filePath" "$tempFileName" } httpSingleUpload() { case "$configuredUploadClient" in curl) response=$( curl --progress-bar --upload-file $1 "https://free.keep.sh" | tee /dev/null) || { echo "Failure!"; return 1;};; wget) response=$(wget --progress=dot --method PUT --body-file="$1" "https://free.keep.sh" | tee /dev/null) || { echo "Failure!"; return 1;} ;; esac echo "Success!" } printUploadResponse() { fileID=$(echo "$response" | cut -d "/" -f 4) echo "Transfer Download Command: transfer -d desiredOutputDirectory $fileID $tempFileName" echo "Transfer File URL: $response" echo -e "\n\n\t Or scan this QR Code" qrify $response } onetimeUpload() { getConfiguredClient checkInternet || exit 0 getconfiguredUploadClient response=$(curl --progress-bar -T $1 temp.sh) downlink=$(echo "$response") } printOnetimeUpload() { echo -e "\n Download link: $downlink" echo -e "\n\n\t Or scan this QR Code" qrify $downlink } singleDownload() { if [[ ! -d $1 ]];then { echo "Directory doesn't exist, creating it now..."; mkdir -p "$1"; }; fi tempOutputPath=$1 if [ -f "$tempOutputPath/$3" ];then echo -n "File aleady exists at $tempOutputPath/$3, do you want to delete it? [Y/n] "; read -r answer if [[ "$answer" == [Yy] ]] ;then rm -rf "$tempOutputPath"/"$3"; else echo "Stopping download" return 1; fi fi echo "Downloading $3" curl -# -L https://free.keep.sh/$2/$3 > $1/$3 || { echo "Failure"; return 1;} # curl -# -L https://temp.sh/$2/$3 > $1/$3 || { echo "Failure"; return 1;} echo "Success!" } usage() { cat <&2 exit 1 ;; h) usage exit 0 ;; v) echo "Version $currentVersion" exit 0 ;; u) getConfiguredClient || exit 1 checkInternet || exit 1 update || exit 1 exit 0 ;; o) onetime="true" ;; d) down="true" if [ $# -lt 4 ]; then echo "Error: not enough arguments for downloading a file, see the usage"; exit 1 fi if [ $# -gt 4 ]; then echo "Error: to many enough arguments for downloading a file, see the usage"; exit 1 fi inputFilePath=$(echo "$*" | sed s/-d//g | sed s/-o//g | cut -d " " -f 2) inputID=$(echo "$*" | sed s/-d//g | sed s/-o//g | cut -d " " -f 3) inputFileName=$(echo "$*" | sed s/-d//g | sed s/-o//g | cut -d " " -f 4) ;; :) echo "Option -$OPTARG requires an argument." >&2 exit 1 ;; esac done if [[ $# == "0" ]]; then usage exit 0 elif [[ $# == "1" ]];then if [[ $1 == "help" ]]; then usage exit 0 elif [[ $1 == "update" ]]; then getConfiguredClient || exit 1 checkInternet || exit 1 update || exit 1 exit 0 elif [ -f "$1" ];then getConfiguredClient || exit 1 checkInternet || exit 1 getconfiguredUploadClient || exit 1 singleUpload "$1" || exit 1 printUploadResponse exit 0 else echo "Error: invalid filepath" exit 1 fi else if $down ;then getConfiguredClient || exit 1 checkInternet || exit 1 getConfiguredDownloadClient || exit 1 singleDownload "$inputFilePath" "$inputID" "$inputFileName" || exit 1 exit 0 elif ! $down && ! $onetime; then getConfiguredClient || exit 1 checkInternet || exit 1 getconfiguredUploadClient || exit 1 for path in "$@";do singleUpload "$path" || exit 1 printUploadResponse echo done exit 0 elif ! $down && $onetime; then getConfiguredClient || exit 1 if [[ $configuredClient -ne "curl" ]];then echo "Error: curl must be installed to use one time file upload" exit 1 fi inputFileName=$(echo "$*" | sed s/-o//g | cut -d " " -f 2 ) onetimeUpload "$inputFileName" printOnetimeUpload fi fi ================================================ FILE: uninstall.sh ================================================ #!/usr/bin/env bash # Author: Alexander Epstein https://github.com/alexanderepstein declare -a tools=(bak2dvd bash-snippets cheat cloudup crypt cryptocurrency currency geo gist lyrics meme movies newton pwned qrify short siteciphers stocks taste todo transfer weather ytview) all="1" askUninstall() { if [[ -f /usr/local/bin/$1 ]]; then echo -n "Do you wish to uninstall $1 [Y/n]: " read -r answer if [[ "$answer" == [Yy] ]]; then echo -n "Removing $1: " rm -f /usr/local/bin/"$1" > /dev/null 2>&1 || { echo "Failed" ; echo "Error removing file, try running uninstall script as sudo"; exit 1; } echo "Success" else all="0" fi unset answer fi } removeTool() { if [[ -f /usr/local/bin/$1 ]]; then echo -n "Removing $1: " rm -f /usr/local/bin/"$1" > /dev/null 2>&1 || { echo "Failed" ; echo "Error removing file, try running uninstall script as sudo"; exit 1; } echo "Success" fi } removeManpage() { if [ -f "/usr/local/man/man1/bash-snippets.1" ]; then rm -f "usr/local/man/man1/bash-snippets.1" || { echo "Error removing manpage, try running uninstall script as sudo"; exit 1; } ; fi if [ -f "/usr/local/share/man/man1/bash-snippets.1" ]; then rm -f "/usr/local/share/man/man1/bash-snippets.1" || { echo "Error removing manpage, try running uninstall script as sudo"; exit 1; } ; fi } if [[ $1 != "all" ]]; then for tool in "${tools[@]}"; do askUninstall "$tool" || exit 1 done else for tool in "${tools[@]}"; do removeTool "$tool" || exit 1 done fi if [[ $all == "1" ]]; then removeManpage || exit 1 fi ================================================ FILE: weather/weather ================================================ #!/usr/bin/env bash # Author: Alexander Epstein https://github.com/alexanderepstein currentVersion="1.23.0" #This version variable should not have a v but should contain all other characters ex Github release tag is v1.2.4 currentVersion is 1.2.4 LANG="${LANG:-en}" locale=$(echo "$LANG" | cut -c1-2) unset configuredClient if [[ $(echo "$locale" | grep -Eo "[a-z A-Z]*" | wc -c) != 3 ]]; then locale="en"; fi ## This function determines which http get tool the system has installed and returns an error if there isnt one getConfiguredClient() { if command -v curl &>/dev/null; then configuredClient="curl" elif command -v wget &>/dev/null; then configuredClient="wget" elif command -v http &>/dev/null; then configuredClient="httpie" elif command -v fetch &>/dev/null; then configuredClient="fetch" else echo "Error: This tool requires either curl, wget, httpie or fetch to be installed\." >&2 return 1 fi } ## Allows to call the users configured client without if statements everywhere httpGet() { case "$configuredClient" in curl) curl -A curl -s "$@" ;; wget) wget -qO- "$@" ;; httpie) http -b GET "$@" ;; fetch) fetch -q "$@" ;; esac } getIPWeather() { country=$(httpGet ipinfo.io/country) > /dev/null ## grab the country if [[ $country == "US" ]]; then ## if were in the us id rather not use longitude and latitude so the output is nicer city=$(httpGet ipinfo.io/city) > /dev/null region=$(httpGet ipinfo.io/region) > /dev/null if [[ $(echo "$region" | wc -w) == 2 ]];then region=$(echo "$region" | grep -Eo "[A-Z]*" | tr -d "[:space:]") fi httpGet $locale.wttr.in/"$city","$region""$1" else ## otherwise we are going to use longitude and latitude location=$(httpGet ipinfo.io/loc) > /dev/null httpGet $locale.wttr.in/"$location""$1" fi } getLocationWeather() { args=$(echo "$@" | tr " " + ) httpGet $locale.wttr.in/"${args}" } checkInternet() { httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request } update() { # Author: Alexander Epstein https://github.com/alexanderepstein # Update utility version 2.2.0 # To test the tool enter in the defualt values that are in the examples for each variable repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then echo "Error: update utility has not been configured correctly." >&2 exit 1 elif [[ $latestVersion == "" ]]; then echo "Error: no active internet connection" >&2 exit 1 else if [[ "$latestVersion" != "$currentVersion" ]]; then echo "Version $latestVersion available" echo -n "Do you wish to update $repositoryName [Y/n]: " read -r answer if [[ "$answer" == [Yy] ]]; then cd ~ || { echo 'Update Failed'; exit 1; } if [[ -d ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi echo -n "Downloading latest version of: $repositoryName." git clone -q "https://github.com/$githubUserName/$repositoryName" && touch .BSnippetsHiddenFile || { echo "Failure!"; exit 1; } & while [ ! -f .BSnippetsHiddenFile ]; do { echo -n "."; sleep 2; };done rm -f .BSnippetsHiddenFile echo "Success!" cd $repositoryName || { echo 'Update Failed'; exit 1; } git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit." chmod a+x install.sh #this might be necessary in your case but wasnt in mine. ./$nameOfInstallFile "update" || exit 1 cd .. rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; } else exit 1 fi else echo "$repositoryName is already the latest version" fi fi } usage() { cat <&2 exit 1 ;; h) usage exit 0 ;; v) echo "Version $currentVersion" exit 0 ;; u) checkInternet || exit 1 # check if we have a valid internet connection if this isnt true the rest of the script will not work so stop here update || exit 1 exit 0 ;; :) echo "Option -$OPTARG requires an argument." >&2 exit 1 ;; esac done if [[ $# == "0" ]]; then checkInternet || exit 1 getIPWeather || exit 1 exit 0 elif [[ $1 == "help" || $1 == ":help" ]]; then usage exit 0 elif [[ $1 == "update" ]]; then checkInternet || exit 1 update || exit 1 exit 0 fi checkInternet || exit 1 if [[ $1 == "m" ]]; then getIPWeather "?m" || exit 1 elif [[ "${@: -1}" == "m" ]];then args=$( echo "${@:1:(($# - 1))}" ?m | sed s/" "//g) getLocationWeather "$args" || exit 1 elif [[ $1 == "M" ]]; then getIPWeather "?M" || exit 1 elif [[ "${@: -1}" == "M" ]];then args=$( echo "${@:1:(($# - 1))}" ?M | sed s/" "//g) getLocationWeather "$args" || exit 1 elif [[ $1 == "mM" || $1 == "Mm" ]]; then getIPWeather "?m?M" || exit 1 elif [[ "${@: -1}" == "mM" || "${@:-1}" == "Mm" ]];then args=$( echo "${@:1:(($# - 1))}" ?m?M | sed s/" "//g) getLocationWeather "$args" || exit 1 elif [[ $1 == "iM" || $1 == "Mi" ]]; then getIPWeather "?u?M" || exit 1 elif [[ "${@: -1}" == "iM" || "${@:-1}" == "Mi" ]];then args=$( echo "${@:1:(($# - 1))}" ?u?M | sed s/" "//g) getLocationWeather "$args" || exit 1 elif [[ $1 == "i" ]]; then getIPWeather "?u" || exit 1 elif [[ "${@: -1}" == "i" ]];then args=$( echo "${@:1:(($# - 1))}" ?u | sed s/" "//g) getLocationWeather "$args" || exit 1 else getLocationWeather "$@" || exit 1 fi ================================================ FILE: ytview/ytview ================================================ #!/usr/bin/env bash # Author: Linyos Torovoltos https://github.com/linyostorovovoltos # Modifications: Alexander Epstein https://github.com/alexanderepstein if [[ -d $HOME/.cache/ytview ]]; then rm -rf "$HOME"/.cache/ytview/; fi player="" configuredClient="" currentVersion="1.23.0" flag="" ## This function determines which http get tool the system has installed and returns an error if there isnt one getConfiguredClient() { if command -v curl &>/dev/null; then configuredClient="curl" elif command -v wget &>/dev/null; then configuredClient="wget" elif command -v http &>/dev/null; then configuredClient="httpie" elif command -v fetch &>/dev/null; then configuredClient="fetch" else echo "Error: This tool requires either curl, wget, httpie or fetch to be installed\." >&2 return 1 fi } ## Allows to call the users configured client without if statements everywhere httpGet() { case "$configuredClient" in curl) curl -A curl -s "$@" ;; wget) wget -qO- "$@" ;; httpie) http -b GET "$@" ;; fetch) fetch -q "$@" ;; esac } checkInternet() { httpGet github.com > /dev/null 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request } update() { # Author: Alexander Epstein https://github.com/alexanderepstein # Update utility version 2.2.0 # To test the tool enter in the defualt values that are in the examples for each variable repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then echo "Error: update utility has not been configured correctly." >&2 exit 1 elif [[ $latestVersion == "" ]]; then echo "Error: no active internet connection" >&2 exit 1 else if [[ "$latestVersion" != "$currentVersion" ]]; then echo "Version $latestVersion available" echo -n "Do you wish to update $repositoryName [Y/n]: " read -r answer if [[ "$answer" == [Yy] ]]; then cd ~ || { echo 'Update Failed'; exit 1; } if [[ -d ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi echo -n "Downloading latest version of: $repositoryName." git clone -q "https://github.com/$githubUserName/$repositoryName" && touch .BSnippetsHiddenFile || { echo "Failure!"; exit 1; } & while [ ! -f .BSnippetsHiddenFile ]; do { echo -n "."; sleep 2; };done rm -f .BSnippetsHiddenFile echo "Success!" cd $repositoryName || { echo 'Update Failed'; exit 1; } git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit." chmod a+x install.sh #this might be necessary in your case but wasnt in mine. ./$nameOfInstallFile "update" || exit 1 cd .. rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; } else exit 1 fi else echo "$repositoryName is already the latest version" fi fi } getConfiguredPlayer() { if [ ! -z "${YTVIEWPLAYER+x}" ]; then player="$YTVIEWPLAYER" return 0 fi if [[ $(uname -s) == "Linux" ]]; then if command -v vlc &>/dev/null; then player="vlc" elif command -v mpv &>/dev/null; then player="mpv" elif command -v mplayer &>/dev/null; then player="mplayer" else echo "Error: no supported video player installed (vlc, mpv or mplayer)" >&2 return 1 fi elif [[ $(uname -s) == "Darwin" ]]; then if [[ -f /Applications/VLC.app/Contents/MacOS/VLC ]]; then player="/Applications/VLC.app/Contents/MacOS/VLC" elif [[ -f $HOME/Applications/VLC.app/Contents/MacOS/VLC ]]; then player="$HOME/Applications/VLC.app/Contents/MacOS/VLC" elif command -v mpv &>/dev/null; then player="mpv" elif [[ -f /Applications/mpv.app/Contents/MacOS/mpv ]]; then player="/Applications/mpv.app/Contents/MacOS/mpv" elif [[ -f $HOME/Applications/mpv.app/Contents/MacOS/mpv ]]; then player="$HOME/Applications/mpv.app/Contents/MacOS/mpv" else if [[ $(mdutil -s / | grep "Indexing enabled." 2>/dev/null) != "" ]]; then vlc_md=$(mdfind kMDItemCFBundleIdentifier = "org.videolan.vlc" 2>/dev/null) if [[ $vlc_md != "" ]]; then player="$vlc_md/Contents/MacOS/VLC" else mpv_md=$(mdfind kMDItemCFBundleIdentifier = "io.mpv" 2>/dev/null) if [[ $mpv_md != "" ]]; then player="$mpv_md/Contents/MacOS/mpv" else echo "Error: no supported video player installed (VLC or mpv)" >&2 return 1 fi fi else echo "Error: no supported video player installed (VLC or mpv)" >&2 return 1 fi fi fi } # Get the video titles channelview() { mkdir -p "$HOME"/.cache/ytview/channels/"$channel" || return 1 httpGet "https://www.youtube.com/user/$channel/videos?hl=en" | grep "Duration" | awk '{print $10 " " $11 " " $12 " " $13 " " $14 " " $15 " " $16 " " $17 " " $18 " " $19 " " $20 " " $21 " " $22 " " $23 " " $24 " " $25 " " $26 " " $27 " " $29}' | sed 's/aria-describedby="description-id.*//' | sed s/title=// | sed 's/"//' | sed 's/"//' | awk '{printf "%s.\t%s\n",NR,$0}' | sed s/'''/"'"/g | sed s/'&'/'and'/g | sed s/\"\;/\"/g > "$HOME"/.cache/ytview/channels/"$channel"/titles.txt || return 1 # Get the video urls httpGet "https://www.youtube.com/user/$channel/Videos?hl=en" | grep "watch?v=" | awk '{print $6}' | sed s/spf-link// | sed s/href=// | sed 's/"//' | sed 's/"//' | sed '/^\s*$/d' | sed 's/\//https:\/\/www.youtube.com\//' | awk '{printf "%s.\t%s\n",NR,$0}' > "$HOME"/.cache/ytview/channels/"$channel"/urls.txt || return 1 # Print 20 first video titles for the user to choose from head -n 20 "$HOME"/.cache/ytview/channels/"$channel"/titles.txt || return 1 # Prompt the user for video number read -p "Choose a video: " titlenumber if [[ -n ${titlenumber//[0-9]/} ]]; then echo "Canceled." >&2 exit 0 fi # Play the video with your player $player $(sed -n $(echo "$titlenumber")p < "$HOME"/.cache/ytview/channels/"$channel"/urls.txt | awk '{print $2}') > /dev/null 2>&1 & } searchview() { search=$(echo "$search" | tr " " + ) mkdir -p "$HOME"/.cache/ytview/searches/"$search" #Get video titles httpGet "https://www.youtube.com/results?hl=en&search_query=$search" | grep "Duration" | grep "watch?v=" | awk '{print $13 " " $14 " " $15 " " $16 " " $17 " " $18 " " $19 " " $20 " " $21 " " $22 " " $23 " " $23}' | sed 's/aria-describedby="description-id.*//g' | sed s/title=// | sed 's/"//g' | sed s/spf-link// | sed 's/data-session-link=itct*.//' | sed s/spf-prefetch//g | sed 's/rel=//g' | sed 's/"//' | awk '{printf "%s.\t%s\n",NR,$0}' | sed s/'''/"'"/g | sed s/'&'/'and'/g | sed s/\"\;/\"/g > "$HOME"/.cache/ytview/searches/"$search"/titles.txt || return 1 #Get video urls httpGet "https://www.youtube.com/results?hl=en&search_query=$search" | grep "watch?v=" | awk '{print $5}' | sed s/vve-check// | sed 's/href="/https:\/\/www.youtube.com/' | sed 's/"//' | sed s/class="yt-uix-tile-link"// | sed '/^\s*$/d' | awk '{printf "%s.\t%s\n",NR,$0}' > "$HOME"/.cache/ytview/searches/"$search"/urls.txt || return 1 #Print 20 first video titles for the user to choose from cat "$HOME"/.cache/ytview/searches/"$search"/titles.txt || return 1 #Let the user choose the video number read -p "Choose a video: " titlenumber if [[ -n ${titlenumber//[0-9]/} ]]; then echo "Canceled." >&2 exit 0 fi #Play the video with your favorite player $player $(sed -n $(echo "$titlenumber")p < "$HOME"/.cache/ytview/searches/"$search"/urls.txt | awk '{print $2}') > /dev/null 2>&1 & } usage() { cat <&2 exit 1 fi ;; c) if [[ $flag != "search" ]]; then channel="$OPTARG" flag="channel" else echo "Error: search and channel options are mutually exclusive" >&2 exit 1 fi ;; h) usage && exit 0 ;; u) checkInternet && update && exit 0 || exit 1;; v) echo "Version $currentVersion" && exit 0 ;; *) usage && exit 0 ;; esac done if [[ $# == "0" ]]; then usage exit 0 elif [[ $1 == "help" ]]; then usage exit 0 elif [[ $1 == "update" ]]; then checkInternet || exit 1 update exit 0 elif [[ $flag == "search" ]]; then checkInternet || exit 1 getConfiguredPlayer || exit 1 searchview || exit 1 elif [[ $flag == "channel" ]]; then checkInternet || exit 1 getConfiguredPlayer || exit 1 channelview || exit 1 else checkInternet || exit 1 search=$(printf '%s ' "$@") getConfiguredPlayer || exit 1 searchview || exit 1 fi